.Net PixelFormat有Java等价吗?

时间:2012-04-28 04:27:30

标签: java image-processing pixelformat

Java中的哪些内容与C#PixelFormat's成员匹配。

即。 Format24bppRgb与BufferedImage.TYPE_INT_RGB?

匹配

这是我的代码。我得到的图像有.Net的PixelFormat = Format32bppArgb 我正在创建像这样的BufferedImage:

        int sizeBytes = width * height;
        DataBufferByte dataBuffer = new DataBufferByte(myImageBytes, sizeBytes);

        WritableRaster raster = Raster.createInterleavedRaster(dataBuffer, // dataBuffer
                width, // width
                height, // height
                width * 4, // scanlineStride
                4, // pixelStride
                new int[]{0, 1, 2, 3}, // bandOffsets
                null); // location

        java.awt.image.ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), // ColorSpace
                new int[]{8, 8, 8, 8}, // bits
                true, // hasAlpha
                false, // isPreMultiplied
                ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);

        BufferedImage result = new BufferedImage(colorModel, raster, false, null);

创建bufferedImage后,红色和蓝色交换在其中。

接下来,我尝试按照以下方式创建图像

        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        WritableRaster r = result.getRaster();
        int[] pixels = byteToInt(bytes);
        r.setPixels(0, 0, width, height , pixels); // ! Here an exception occures, because after I converted the byte array to int one the width becomes too long.

通过此方法转换字节数组

private int[] byteToInt(byte[] pixels) {
    int[] ints = new int[pixels.length / 3];
    int byteIdx = 0;
    for (int pixel = 0; pixel < ints.length; pixel++) {
        int red = (int) pixels[byteIdx++] & 0xFF;
        int green = (int) pixels[byteIdx++] & 0xFF;
        int blue = (int) pixels[byteIdx++] & 0xFF;
        int rgb = (red << 16) | (green << 8) | blue;
        ints[pixel] = rgb;
    }
    return ints;
}

现在颜色看起来很好,但我得到了例外

java.lang.ArrayIndexOutOfBoundsException: 27600
at sun.awt.image.ByteInterleavedRaster.setPixels(ByteInterleavedRaster.java:1106)

如果我使用较小的宽度(例如宽度/ 3),颜色看起来很好,但图片本身会缩小。

我有点坚持这个问题。任何帮助表示赞赏。感谢。

1 个答案:

答案 0 :(得分:1)

BufferedImage绝对是一个很好的起点。 PixelFormat中的许多值将与BufferedImage中的值匹配 - 它们各自具有24位和32位RGB / ARGB值,均具有5-5-5和5-6-5组合等

如果您遇到问题,请发布一些代码,我们会看一下,尝试提供帮助。我建议的方法是使用字节顺序(在像素int中),直到得到你期望的结果 - 尝试将BufferedImage绘制到像JPanel这样的GUI对象上,这样你就可以了可以看到它的样子。

如果你的像素值有一个int []数组,这就是我通常用来将数组显示为图像的代码......

int[] pixels;
ColorModel model = new DirectColorModel(32,0x00ff0000,0x0000ff00,0x000000ff,0xff000000);
Image image = new JLabel().createImage(new MemoryImageSource(width,height,model,pixels,0,width));