【问题标题】:How to convert raster byte array of an image to original image in java?如何将图像的光栅字节数组转换为java中的原始图像?
【发布时间】:2015-02-02 16:35:31
【问题描述】:

我需要将图像的字节转换为原始图像。我的字节数组是由 WritableRaster 创建的。它试图转换为原始形式,但它产生的图像没有原始颜色。我的尝试如下

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

【问题讨论】:

  • 您如何将光栅转换回“原始”图像? BufferedImage 由 Raster 和 ColorModel 组成。 ColorModel 知道如何解释图像数据。
  • 我是这样处理colormodel的

标签: java image image-processing raster


【解决方案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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 2020-12-27
    • 2020-05-24
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多