How to convert raster byte array of an image to original image in java?

孤街浪徒 提交于 2021-01-28 01:43:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!