javaimageimagemagickrgbjmagick

How to convert an indexed image to a RGB image in Java?


I have a color indexed TIFF image (8-bits) and I want to convert it to a RGB 24-bits image (not indexed). What would be the way to do that?

I'm using JMagick. In a weird way, it works fine for indexed 8-bits images that are grayscale when i use:

image.transformRgbImage(info.getColorspace());

even if the image, though not indexed any more, is still 8-bits after that, which is lucky as it is grayscale and should actually be 8-bits. The weird stuff is that the transformRgbImage() performs that although I'd rather expect it to convert the image to a 24-bits one. Anyway...

The same way doesn't work for a color indexed 8-bits image. I just don't know how to use the JMagick API to achieve that goal. I tried setting:

image.setDepth(24);

or:

info.setDepth(24);

but both result in an EXCEPTION_ACCESS_VIOLATION. When I set:

info.setDepth(32);

no exception is raised, 1) but the image is 32-bits, which shouldn't be, and 2) it is all black (1 unique color). Why does the setDepth(24) raises such an exception?? How should I do?

Thanks in advance for your help.


Solution

  • I dont know about jmagick, but generally once you created an image object its properties are fixed (size and color model).

    You don't change an images properties, you create a new image with the desired target properties and paint your original image into the new image. In plain core java you would simply do it like this:

    public BufferedImage toRGB(Image i) {
        BufferedImage rgb = new BufferedImage(i.getWidth(null), i.getHeight(null), BufferedImage.TYPE_INT_RGB);
        rgb.createGraphics().drawImage(i, 0, 0, null);
        return rgb;
    }