Java 字节数组到图像对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1580038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Byte Array to Image object
提问by Se?or Reginold Francis
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?
我在 Java 中得到一个 byte[] 数组,其中包含图像的字节,我需要将其输出到图像中。我该怎么做呢?
Much thanks
非常感谢
采纳答案by Nick Veys
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
回答by Platinum Azure
According to the Java docs, it looks like you need to use the MemoryImageSource Classto put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).
根据 Java 文档,看起来您需要使用MemoryImageSource 类将字节数组放入内存中的对象中,然后接下来使用 Component.createImage(ImageProducer) (传入实现 ImageProducer 的 MemoryImageSource)。
回答by Kevin Loney
Since it sounds like you already know what format the byte[] array is in (e.g. 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.
由于听起来您已经知道 byte[] 数组的格式(例如 RGB、ARGB、BGR 等),您可以使用BufferedImage.setRGB(...)或BufferedImage.getRaster()的组合和WritableRaster.setPixels(...)或WritableRaster.setSamples(...)。不幸的是,这两种方法都需要您将 byte[] 转换为 int[]、float[] 或 double[] 之一,具体取决于图像格式。
回答by Sam Barnum
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.
如果您知道图像的类型并且只想生成一个文件,则无需获取 BufferedImage 实例。只需将字节写入具有正确扩展名的文件即可。
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
out.write(bytes);
}
回答by Usman
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);