JAI: How to convert 4-band 32-bits CMYK image into

2019-08-01 07:25发布

问题:

I'm trying to convert a image into PNG format, the data I have is a 4-band 32-bits TIFF-like image compressed by LZW. By using Java2D and JAI now I have data uncompressed to represent colors in CMYK space and it can be exported and viewed when stored in tiff with the same settings as 4 band 32-bit format.

The problem is when I try converting to other formats like PNG it produce zero-sized data, so I'd like to ask is there anyone have similar experience on converting such image? I have some of my code pasted as below for your reference, please also correct if you found any mistake, thanks!!

int bands = 4;
int w = sizeParam.getHorizonPts();
int h = sizeParam.getVerticalPts();
ColorModel cm = new ComponentColorModel(new CMYKColorSpace(), new int[]{8,8,8,8},
                false, false, Transparency.OPAQUE, DataBuffer.TYPE_FLOAT);

// Create WritableRaster with four bands
WritableRaster r = RasterFactory.createBandedRaster(
                DataBuffer.TYPE_FLOAT, w, h, bands, null);
for (int i = 0; i < bandStreams.length; i++) {
        int x, y;
        x = y = 0;
        byte[] uncomp = new byte[w * h];
        decoder.decode(bandStreams[i], uncomp, h);
        for (int pos = 0; pos < uncomp.length; pos++) {
                r.setSample(x++, y, i, (float) (uncomp[pos] & 0xff) / 255);
                if (x >= w) {
                        x = 0;
                        y++;
                }
        }
}

// Create TiledImage
TiledImage tiledImage = new TiledImage(0, 0, w, h, 0, 0,
                RasterFactory.createBandedSampleModel(DataBuffer.TYPE_FLOAT, w,
                                h, bands), cm);
tiledImage.setData(r);
JAI.create("filestore", tiledImage, "test.tif", "TIFF");

回答1:

I finally solved this by converting CMYK to RGB so it can generate PNG image, the following code is used during the course,

// Create target image with RGB color.
BufferedImage result = new BufferedImage(w, h,
            BufferedImage.TYPE_INT_RGB);

// Convert pixels from YMCK to RGB.
ColorConvertOp cmykToRgb = new ColorConvertOp(new CMYKColorSpace(),
            result.getColorModel().getColorSpace(), null);
cmykToRgb.filter(r, result.getRaster());