coobird / thumbnailator

Thumbnailator - a thumbnail generation library for Java
MIT License
5.14k stars 784 forks source link

Thumbnail background is black for GIF images with transparent background #123

Open arn1995 opened 6 years ago

arn1995 commented 6 years ago

I am trying to create thumbnails from images with .gif format having transparent backgrounds. I am creating thumbnails of dimensions 200x200 in .jpg format. I ahve numerous solutions suggested in previous issues to no effect. I have also tried to change the output format to something and still drawn blank.

Expected behavior

The result that comes must have a white or transparent background.

Actual behavior

The images come with a black background

Steps to reproduce the behavior

I am using the following methodology to create the thumbnail.

Thumbnails.of(inFile).size(200, 200).outputFormat("jpg").toOutputStream(os);

Here, the "inFile" has the image input and "os" is the FileOutputStream in which retrieving the thumbnail and saving it into another file to be uploaded. I have checked with all the download and upload features and none of them are interfering with this procedure or causing any problems.

Environment

cassandra_tiny_titans_001 This is the original image.

lcs7450093368546624984 This is the thumbnail being generated.

itll commented 6 years ago
/**
 *将透明背景设置为白色
 */
public class ThumbnailsImgFilter implements ImageFilter {
    @Override
    public BufferedImage apply(BufferedImage img) {
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphic = newImage.createGraphics();
        graphic.setColor(Color.white);//white
        graphic.fillRect(0, 0, w, h);
        graphic.drawRenderedImage(img, null);
        graphic.dispose();
        return newImage;
    }
}

@Test
public void testFile() throws IOException {
        String fileNamess = "E://1.png";//原图
        String resoultPath = "E://2.png";//生成的图片
        int width = 60;
        int height = 60;

        //调用addFilter 添加自定义filter
        Thumbnails.of(fileNamess).addFilter(new ThumbnailsImgFilter()).size(width, height).keepAspectRatio(false).toFile(resoultPath);
}

https://my.oschina.net/itll/blog/1601028

coobird commented 6 years ago

Note to self: Check if issue is same as #41.