问题
I need to convert bytes of an image to original image. My byte array which is created by WritableRaster.And Itried to convert to original form ,but it produced image without original colors.My tries are below
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();
}
回答1:
I figured out what's wrong with your code:
change this line:
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[]{0, 1, 2}, (Point) null);
to
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[]{2, 1, 0}, (Point) null);
will work because the original image data is in BGR format instead of RGB.
来源:https://stackoverflow.com/questions/28282368/how-to-convert-raster-byte-array-of-an-image-to-original-image-in-java