简体   繁体   中英

Byte Array to Image object

I am given a byte[] array in Java which contains the bytes for an image, and I need to output it into an image. How would I go about doing this?

Much thanks

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

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

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);

Since it sounds like you already know what format the byte[] array is in (eg RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...) , or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...) . Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

根据 Java 文档,看起来您需要使用MemoryImageSource 类将字节数组放入内存中的对象中,然后接下来使用 Component.createImage(ImageProducer) (传入实现 ImageProducer 的 MemoryImageSource)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM