2013-03-14 49 views
39

我看到有很多人有類似的問題,但我還沒有嘗試找到我正在尋找的東西。Java:緩衝圖像到字節數組並返回

所以,我有讀取輸入圖像,並將其轉換爲字節數組的方法:

File imgPath = new File(ImageName); 
    BufferedImage bufferedImage = ImageIO.read(imgPath); 
    WritableRaster raster = bufferedImage .getRaster(); 
    DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); 

我現在想要做的就是將其轉換回一個BufferedImage(我有一個針對應用程序我需要這個功能)。請注意,「測試」是字節數組。

BufferedImage img = ImageIO.read(new ByteArrayInputStream(test)); 
    File outputfile = new File("src/image.jpg"); 
    ImageIO.write(img,"jpg",outputfile); 

然而,這將返回以下異常:

Exception in thread "main" java.lang.IllegalArgumentException: im == null! 

這是因爲BufferedImage的IMG爲空。我認爲這與事實有關,在我從BufferedImage到字節數組的原始轉換中,信息被改變/丟失,使得數據不能再被識別爲jpg。

有沒有人有任何建議如何解決這個問題?將不勝感激。

回答

58

這是建議通過查看其源/文件轉換爲字節數組

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
ImageIO.write(img, "jpg", baos); 
byte[] bytes = baos.toByteArray(); 
+3

沖洗和關閉會做沒有什麼 – 2014-02-28 10:57:36

+6

在這裏使用jpg有沒有特別的理由? – hguser 2014-07-03 08:52:11

+1

如果close()沒有做任何事情,它會調用flush()本身,並且有必要在* toByteArray()之前調用它,而不是在它之後調用它。 – EJP 2014-08-03 23:54:11

6

請注意,調用closeflush不會做任何事情,你可以看到自己這一點:

關閉一個ByteArrayOutputStream不起作用。

OutputStream的flush方法什麼都不做。

因此使用這樣的:

ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT); 
boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos); 
assert foundWriter; // Not sure about this... with jpg it may work but other formats ? 
byte[] bytes = baos.toByteArray(); 

下面是關於大小的提示幾個環節: