我正在从 png 图像获取 int 数组,如何将其转换为 bufferdimage 或创建新的 PNG 文件?
int[] pixel = new int[w1*h1];
int i = 0;
for (int xx = 0; xx < h1; xx++) {
for (int yy = 0; yy < w1; yy++) {
pixel[i] = img.getRGB(yy, xx);
i++;
}
}
最佳答案
如果你有一个整数数组,它是打包的 RGB 值,这是将它保存到文件的 java 代码:
int width = 100;
int height = 100;
int[] rgbs = buildRaster(width, height);
DataBuffer rgbData = new DataBufferInt(rgbs, rgbs.length);
WritableRaster raster = Raster.createPackedRaster(rgbData, width, height, width,
new int[]{0xff0000, 0xff00, 0xff},
null);
ColorModel colorModel = new DirectColorModel(24, 0xff0000, 0xff00, 0xff);
BufferedImage img = new BufferedImage(colorModel, raster, false, null);
String fname = "/tmp/whatI.png";
ImageIO.write(img, "png", new File(fname));
System.out.println("wrote to "+fname);
数组 0xff0000, 0xff00, 0xff
的原因是 RGB 字节在最低有效字节中用蓝色打包。如果您打包不同的整数,请更改该数组。
关于java - 从 RGB 数据的 int 数组创建 PNG 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031316/