如何在Java中将图像的光栅字节数组转换为原始图像? [英] How to convert raster byte array of an image to original image in java?

查看:72
本文介绍了如何在Java中将图像的光栅字节数组转换为原始图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图像的字节转换为原始图像.我的字节数组是由WritableRaster创建的,然后尝试转换为原始格式,但是生成的图像没有原始颜色.我的尝试如下

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();
}

推荐答案

我发现您的代码出了什么问题:

I figured out what's wrong with your code:

更改此行:

WritableRaster栅格= Raster.createInterleavedRaster(缓冲区,宽度,高度,3 *宽度,3,新int [] {0,1,2},(Point)null);

WritableRaster栅格= Raster.createInterleavedRaster(缓冲区,宽度,高度,3 *宽度,3,新int [] {2,1,0},(Point)null);

将起作用,因为原始图像数据是BGR格式而不是RGB.

will work because the original image data is in BGR format instead of RGB.

这篇关于如何在Java中将图像的光栅字节数组转换为原始图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆