我有一个具有透明度的TYPE_4BYTE_ABGR imageType的BufferedImage,我想将其转换为TYPE_3BYTE_BGR BufferedImage.我试图在TYPE_3BYTE_BGR上绘制TYPE_4BYTE_ABGR图像,但它改变了颜色.
目的是将透明图像放在白色背景上,因为如果只是将TYPE_4BYTE_AGBR图像写入.jpg,他就会获得黑色透明区域.
解决方法:
这是您需要的代码,您必须在具有Alpha通道的新图像中使用100%alpha的相同颜色.
// 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;
}
如果你想在白色背景上放置透明图像,你应该使用不同类型的新BufferedImage.这样做的代码是这样的:
// 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;
}