简体   繁体   中英

Resize a byte array image in pixels

I have an image stored as a byte array. Regardless how large the size, I want to always resize it down to 100x100 pixels.

I am trying to convert the byte array into a bufferedimage, resize and save it back as a bytearray. But with the following code, the images no longer appear on my page.

byte[] pict; // this array contains the image
BufferedImage bufferedImage;

ByteArrayInputStream bais = new ByteArrayInputStream(pict);
try {
    bufferedImage = ImageIO.read(bais);
    bufferedImage = Scalr.resize(bufferedImage, 100);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write( bufferedImage, "jpg", baos );
    baos.flush();

    pict = baos.toByteArray();
    baos.close();

} catch (IOException e) {
    throw new RuntimeException(e);
}
OutputStream o = response.getOutputStream();
o.write(pict); 

Do it this way instead:

Image tmpImage = ImageIO.read(bais);
Image scaled = tmpImage.getScaledInstance(100, 100, Image.SCALE_SMOOTH);

Then, to convert to a byte array, convert the image into a bufferedimage and then that into the byte array:

BufferedImage buffered = ((ToolkitImage) scaled).getBufferedImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "jpg", baos);
baos.flush();
pict = baos.toByteArray();
baos.close();

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