我在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[]之一,具体取决于图像格式。