4

I have a BufferedImage of TYPE_4BYTE_ABGR imageType with transparency and I want to convert it into TYPE_3BYTE_BGR BufferedImage. I tried to draw TYPE_4BYTE_ABGR image on TYPE_3BYTE_BGR one, but it changed colors.

The aim is to put transparent image on white background, because if one just writes TYPE_4BYTE_AGBR image into .jpg, he gets black ob transparent area.

1 Answers1

1

This is the code that you need, you have to put the same color with 100% alpha in a new image with alpha channel.

// bufferedImage is your image.
if (bufferedImage.getType() == BufferedImage.TYPE_3BYTE_BGR) {
    BufferedImage bff = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
    for (int y = 0; y < bufferedImage.getHeight(); ++y) {
        for (int x = 0; x < bufferedImage.getWidth(); ++x) {
        int argb = bufferedImage.getRGB(x, y);
        bff.setRGB(x, y, argb & 0xFF000000); // same color alpha 100%
        }
    }
    return bff;
} else {
    return bufferedImage;
}

if you want to put a transparent image on a white background you should indeed use a new BufferedImage with different type. The code to do so is this:

// bufferedImage is your image.
if (bufferedImage.getType() == BufferedImage.TYPE_4BYTE_ABGR) {
    for (int y = 0; y < bufferedImage.getHeight(); ++y) {
        for (int x = 0; x < bufferedImage.getWidth(); ++x) {
            int argb = bufferedImage.getRGB(x, y);
            if((argb & 0x00FFFFFF) == 0x00FFFFFF){ //if the pixel is transparent
                bufferedImage.setRGB(x, y, 0xFFFFFFFF); // white color.
            }
        }
    }
    return bufferedImage;
}
Gianmarco
  • 2,536
  • 25
  • 57