小编典典

JAVA:如何从byte []创建.PNG图像?

java

我看过一些代码源,但是我不明白…

我使用Java 7

请, 如何将RGB (红色,绿色,蓝色) 字节数组 (或类似 格式转换为.PNG文件格式

可能表示“ RGB像素”的数组中的示例:

byte[] aByteArray={0xa,0x2,0xf};

重要方面:

我尝试仅从byte []“ 而不是 从以前的现有文件” 生成.PNG文件

现有的API有可能吗?;)

这是我的第一个代码:

byte[] aByteArray={0xa,0x2,0xf}; 
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray); 
File outputfile = new File("image.png"); 
ImageIO.write(bais, "png", outputfile);

.... 错误: 找不到合适的方法

这里是 Jeremy 修改的另一个版本,但看起来类似:

byte[] aByteArray={0xa,0x2,0xf};
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray); 
final BufferedImage bufferedImage = ImageIO.read(newByteArrayInputStream(aByteArray));
ImageIO.write(bufferedImage, "png", new File("image.png"));

....多个 错误: 图片==空!......确定吗?注意:我不搜索使用源文件


阅读 389

收藏
2020-11-16

共1个答案

小编典典

Image I / O API处理图像,因此您需要先从字节数组中制作图像,然后再将其写入。

byte[] aByteArray = {0xa,0x2,0xf,(byte)0xff,(byte)0xff,(byte)0xff};
int width = 1;
int height = 2;

DataBuffer buffer = new DataBufferByte(aByteArray, aByteArray.length);

//3 bytes per pixel: red, green, blue
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[] {0, 1, 2}, (Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); 
BufferedImage image = new BufferedImage(cm, raster, true, null);

ImageIO.write(image, "png", new File("image.png"));

假定字节数组每个像素有三个字节(红色,绿色然后是蓝色),并且值的范围是0-255。

2020-11-16