Is there a way to set a default color for transparency when using ColorConvertOp in Java2D?
-
17-04-2021 - |
Question
I'm converting an image with transparency in it into a Colorspace that doesn't have transparency. I'd like to set a background color for the transparent areas. Right now when I convert it any area that is transparent turns to black in the final image. Is there a way to do that while I'm converting between ColorSpaces? Here is my code I use to convert between color spaces:
public BufferedImage convertColorspace( BufferedImage source, int newType) {
BufferedImage destination = new BufferedImage( source.getWidth(), source.getHeight(), newType);
ColorConvertOp colorConvertOp = new ColorConvertOp(null);
colorConvertOp.filter(source, destination);
return destination;
}
// here is how its used
BufferedImage converted = convertColorspace(combinedImage, BufferedImage.TYPE_3BYTE_BGR);
I'm converting from BufferedImage.TYPE_4BYTE_ARGB to BufferedImage.TYPE_3BYTE_BGR.
Solution
How about:
BufferedImage temp = new BufferedImage(source.getWidth(), source.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = temp.createGraphics();
g2.setColor(Color.green);
g2.fillRect(0, 0, source.getWidth(), source.getHeight());
g2.drawImage(0, 0, source, null);
g2.dispose();
Then call colorConvertOp.filter
with temp
instead of source
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow