Converting transparent gif / png to jpeg using java

前端 未结 7 824
南笙
南笙 2020-11-29 02:27

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:

Input gif image http://img292.imagesha

7条回答
  •  执念已碎
    2020-11-29 03:02

    3 months late, but I am having a very similar problem (although not even loading a gif, but simply generating a transparent image - say, no background, a colored shape - where when saving to jpeg, all colors are messed up, not only the background)

    Found this bit of code in this rather old thread of the java2d-interest list, thought I'd share, because after a quick test, it is much more performant than your solution:

            final WritableRaster raster = img.getRaster();
            final WritableRaster newRaster = raster.createWritableChild(0, 0, img.getWidth(), img.getHeight(), 0, 0, new int[]{0, 1, 2});
    
            // create a ColorModel that represents the one of the ARGB except the alpha channel
            final DirectColorModel cm = (DirectColorModel) img.getColorModel();
            final DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask());
    
            // now create the new buffer that we'll use to write the image
            return new BufferedImage(newCM, newRaster, false, null);
    

    Unfortunately, I can't say I understand exactly what it does ;)

提交回复
热议问题