使用java将透明gif / png转换为jpeg [英] Converting transparent gif / png to jpeg using java

查看:267
本文介绍了使用java将透明gif / png转换为jpeg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java将gif图像转换为jpeg。它适用于大多数图像,但我有一个简单的透明gif图像:

I'd like to convert gif images to jpeg using Java. It works great for most images, but I have a simple transparent gif image:

输入gif图像http://img292.imageshack.us/img292/2103/indexedtestal7.gif

[如果图像是缺少:它是一个蓝色圆圈,周围有透明像素]

[In case the image is missing: it's a blue circle with transparent pixels around it]

当我使用以下代码转换此图像时:

When I convert this image using the following code:

File file = new File("indexed_test.gif");
BufferedImage image = ImageIO.read(file);
File f = new File("indexed_test.jpg");
ImageIO.write(image, "jpg", f);

此代码可以在不抛出异常的情况下工作,但会导致无效的jpeg图像:

This code works without throwing an Exception, but results an invalid jpeg image:

输出jpeg图片http://img297.imageshack.us/img297/3493/ indexedtest1qe5.jpg

[如果图像丢失:IE无法显示jpeg,Firefox会显示图像颜色无效。]

[In case the image is missing: IE cannot show the jpeg, Firefox shows the image with invalid colors.]

我正在使用Java 1.5。

I'm using Java 1.5.

我也尝试使用gimp将示例gif转换为png并使用png作为Java代码的输入。结果是一样的。

I also tried converting the sample gif to png with gimp and using the png as an input for the Java code. The result is the same.

这是JDK中的错误吗?如何在没有第三方库的情况下正确转换图像?

Is it a bug in the JDK? How can I convert images correctly preferably without 3rd party libraries?

更新:

答案表明jpeg转换无法正确处理透明度(我仍然认为这是一个错误)并建议使用预定义颜色替换透明像素的解决方法。这两种建议的方法都非常复杂,所以我实现了一个更简单的方法(将作为答案发布)。我接受了第一个已发布的答案(Markus)。我不知道哪种实现更好。我选择了最简单的一个,但我找到了一个不能正常工作的gif。

Answers indicate that jpeg conversion cannot handle transparency correctly (I still think that this is a bug) and suggest a workaround for replacing transparent pixels with predefined color. Both of the suggested methods are quite complex, so I've implemented a simpler one (will post as an answer). I accept the first published answer with this workaround (by Markus). I don't know which implementation is the better. I go for the simplest one still I found a gif where it's not working.

推荐答案

对于Java 6(还有5个,我也是认为):

For Java 6 (and 5 too, I think):

BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
g = bufferedImage.createGraphics();
//Color.WHITE estes the background to white. You can use any other color
g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, null);

这篇关于使用java将透明gif / png转换为jpeg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆