我需要将图像的字节转换为原始图像。我的字节数组由WritableRaster.And创建并转换为原始形式,但它生成的图像没有原始颜色。我的尝试在下面
try {
BufferedImage readImage = ImageIO.read(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg"));
byte imageData[] = get_byte_data(readImage); // Then I need to convert this to original image
DataBuffer buffer = new DataBufferByte(imageData, imageData.length);
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"));
} catch (IOException ex) {
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static byte[] get_byte_data(BufferedImage image) {
WritableRaster raster = image.getRaster();
DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
return buffer.getData();
}
答案 0 :(得分:1)
我弄清楚你的代码有什么问题:
更改此行:
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[]{0, 1, 2}, (Point) null);
到
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[]{2, 1, 0}, (Point) null);
将起作用,因为原始图像数据是BGR格式而不是RGB。