0

the method below return data from InputStream as a string where the string will be constructed using StringBuilder

String getBytes(InputStream is) throws IOException{
   StringBuilder sb = new StringBuilder();
   int ch;
   while ((ch = is.read()) != -1) sb.append((char)ch);
   is.close();
   return sb.toString();
}

but this method doesnt work properly for image data. the best solution is to build the similar method but returning byte[] rather than string. can one show me how?

1 Answer 1

2

Hopefully this is what you are looking for. I'm using this function for my Imgur application which requires an image in the form of a ByteArray.

static File imgFile;
static ByteArrayOutputStream imgStream = new ByteArrayOutputStream();

public static void bufferImage() {
        try {
                BufferedImage bufImg = ImageIO.read(imgFile);
                ImageIO.write(bufImg, getExtension(imgFile), imgStream);
         } catch (IOException ex) {
                System.out.println("Error buffering image");
           }   
    }

I can provide the getExtension function too if you want.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I looked at that question & thought, "Wow, where to begin?". Fortunately you cut straight through to "How to solve". :)
i just used IOUtils.toByteArray(...). unfortunately i got this error : Exception in thread "pool-1-thread-1" java.lang.ExceptionInInitializerError. i got no idea why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.