java – TYPE_ 4BYTE_ ABGR to type_ 3BYTE_ BGR conversion

I have a transparent type_ 4BYTE_ Buffered image of ABGR imagetype. I want to convert it to type_ 3BYTE_ BGR BufferedImage. I tried in type_ 3BYTE_ Draw type on BGR_ 4BYTE_ ABGR image, but it changes color

The purpose is to put the transparent image on a white background, because if you just put type_ 4BYTE_ AgBr image writing Jpg, he will get a black transparent area

Solution

This is the code you need. You must use the same color of 100% alpha in the 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 place a transparent image on a white background, you should use a different type of new bufferedimage The code to do this is as follows:

// 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,0xFFFFFFFF); // white color.
            }
        }
    }
    return bufferedImage;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>