简体   繁体   中英

java image data inputstream

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM