2016-02-19 48 views
3

我将图像存储为字节数组。无论尺寸有多大,我都希望将其缩小至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

做它,而不是这样:

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(); 
+0

如果我这样做,我该如何将它改回字节数组。 – JasSy

+0

更新为能够更改为bytearray。 –

+0

试着用你的代码。图像仍然没有出现。 – JasSy

相关问题