java透明保存JPG变色,使用java将透明gif / png转换为jpeg

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:

[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);

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

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

I'm using Java 1.5.

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.

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

UPDATE:

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值