簡體   English   中英

字節數組到圖像對象

[英]Byte Array to Image object

我在 Java 中得到一個 byte[] 數組,其中包含圖像的字節,我需要將其輸出到圖像中。 我該怎么做呢?

非常感謝

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

如果您知道圖像的類型並且只想生成一個文件,則無需獲取 BufferedImage 實例。 只需將字節寫入具有正確擴展名的文件即可。

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}
From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

由於聽起來您已經知道 byte[] 數組的格式(例如 RGB、ARGB、BGR 等),您可以使用BufferedImage.setRGB(...)BufferedImage.getRaster()的組合和WritableRaster.setPixels(...)WritableRaster.setSamples(...) 不幸的是,這兩種方法都需要您將 byte[] 轉換為 int[]、float[] 或 double[] 之一,具體取決於圖像格式。

根據 Java 文檔,看起來您需要使用MemoryImageSource 類將字節數組放入內存中的對象中,然后接下來使用 Component.createImage(ImageProducer) (傳入實現 ImageProducer 的 MemoryImageSource)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM