2016-02-19 80 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

相關問題