[英]Issues with transparency in a GIF file using ImageIO write function
Preamble: I was trying to save swt ImageData to a gif file but it was throwing "unsupported color depth". 序言:我试图将swt ImageData保存到gif文件,但是它抛出“不受支持的颜色深度”。 I decided to convert the org.eclipse.swt.graphics.ImageData
to java.awt.image.BufferedImage
and it works fine until I started using transparency. 我决定将org.eclipse.swt.graphics.ImageData
转换为java.awt.image.BufferedImage
,在我开始使用透明度之前,它可以正常工作。
Issue: Transparent pixels are not being handled correctly instead they are colored with last foreground color used when painting the GC. 问题:透明像素未得到正确处理,而是使用在绘制GC时使用的最后前景色进行着色。 I noticed this undesired effect was down to this line in my code. 我注意到这种不希望有的效果已经在我的代码中下降到了这一行。
ImageIO.write(bufferedImage, "gif", file);
After doing some web searches I found out that the issue has been resolved in JDK 7 http://ubuntuforums.org/archive/index.php/t-1060128.html 经过一些网络搜索后,我发现该问题已在JDK 7 http://ubuntuforums.org/archive/index.php/t-1060128.html中解决。
The problem is I have to use Java 6 not 7. Can anyone kindly tell me how this can be achieved? 问题是我必须使用Java 6而不是7。有人可以告诉我如何实现它吗?
I had a similar problem. 我有一个类似的问题。 I have ImageData and I am trying to write to GIF or PNG with transparency. 我有ImageData,并且尝试以透明的方式写入GIF或PNG。 I used the following conversion function and it worked for me. 我使用了以下转换函数,它对我有用。
static BufferedImage convertToAWT(ImageData data) {
ColorModel colorModel = null;
PaletteData palette = data.palette;
if (palette.isDirect) {
int alphaMask = 0xff;
colorModel = new DirectColorModel(data.depth, palette.redMask, palette.greenMask, palette.blueMask, alphaMask);
BufferedImage bufferedImage = new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
int pixel = data.getPixel(x, y);
RGB rgb = palette.getRGB(pixel);
// ASSUME that pixel==0 is transparent!!!!
int alpha = (pixel == 0) ? 0 : alphaMask;
bufferedImage.setRGB(x, y, alpha << 24 | rgb.red << 16 | rgb.green << 8 | rgb.blue);
}
}
return bufferedImage;
} else {
return null; // not supported
}
}
private static void writeToFile(Image img, String name)
{
BufferedImage ii = convertToAWT(img.getImageData());
try
{
// You can change this to write GIF or JPG also
ImageIO.write(ii, "PNG", new File(name + ".png"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
Notice that this assumes that pixel zero is transparent. 注意,这假设像素零是透明的。 That maybe not the case for you. 对您而言可能并非如此。 Perhaps you can try other values, like -1 or 255 etc, and see what works. 也许您可以尝试其他值,例如-1或255等,然后查看有效的方法。 Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.