调整字节数组图像的像素大小

3

我有一个以字节数组形式存储的图像。无论大小如何,我都希望将其调整为100x100像素。

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

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个回答

2
请用这种方式代替:
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();

如果我这样做,如何将其转换回字节数组? - JasSy
你想让它出现在什么地方? - Rabbit Guy
图像来自数据库。上述代码以及填充 byte[] pict 的数据库连接代码在 jsp 文件中。我将这些数据发送到另一个 jsp 页面以显示图像。当我 o.write(pict); 写入任何重新调整大小的代码时,数据会正常发送并显示图像。 - JasSy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接