以像素为单位调整字节数组图像的大小

时间:2016-02-19 20:01:32

标签: java

我将图像存储为字节数组。无论大小有多大,我都希望始终将其调整为100x100像素。

我正在尝试将字节数组转换为bufferedimage,调整大小并将其保存为bytearray。但是使用以下代码,图像不再出现在我的页面上。

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); 

1 个答案:

答案 0 :(得分:1)

请这样做:

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

然后,要转换为字节数组,将图像转换为bufferedimage,然后转换为字节数组:

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