ImageIO not able to write a JPEG file

后端 未结 5 1591
萌比男神i
萌比男神i 2020-12-01 06:16

I have a BufferedImage I\'m trying to write to a jpeg file, but my Java program throws an exception. I\'m able to successfully save the same buffer to a gif and png. I\'ve t

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 06:26

    2019 answer: Make sure your BufferedImage does not have alpha transparency. JPEG does not support alpha, so if your image has alpha then ImageIO cannot write it to JPEG.

    Use the following code to ensure your image does not have alpha transparancy:

    static BufferedImage ensureOpaque(BufferedImage bi) {
        if (bi.getTransparency() == BufferedImage.OPAQUE)
            return bi;
        int w = bi.getWidth();
        int h = bi.getHeight();
        int[] pixels = new int[w * h];
        bi.getRGB(0, 0, w, h, pixels, 0, w);
        BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        bi2.setRGB(0, 0, w, h, pixels, 0, w);
        return bi2;
    }
    

提交回复
热议问题