【问题标题】:JAVA : How to create .PNG image from a byte[]?JAVA:如何从 byte[] 创建 .PNG 图像?
【发布时间】:2014-04-17 13:27:03
【问题描述】:

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

我使用 Java 7

如何将 RGB(红、绿、蓝)字节数组(或类似的东西)转换为 .PNG 文件格式 ?

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

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

重要方面:

我尝试仅从 byte[] "not 从以前的现有文件"

生成 .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")); 

....多个错误: image == null! ...... 当然 ?注意:我不搜索使用源文件

【问题讨论】:

  • 能不能把不明白的代码贴出来,我们来帮你。

标签: java arrays image file converter


【解决方案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。

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 2012-06-04
    • 1970-01-01
    • 2014-12-25
    • 2012-05-15
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多