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;
}