序
本文主要来聊一下使用ImageIO在BufferedImage.TYPE_INT_ARGB模式下操作jpg格式图片显示黑色的bug。
bug
- JDK-4712797 : ImageIO fails to decode YCbCr JPEGs that do not have a JFIF marker
- JDK-4776576 : REG: ImageIO reader produces an incorrect image when read as a RenderedImage
复现实例
public void testArgbOnJpg() throws IOException {
int width = 400;
int height = 400;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, width, height);
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
Ellipse2D.Float shape = new Ellipse2D.Float(20, 20, 10, 10);
g2.fill(shape);
g2.dispose();
image.flush();
ImageIO.write(image,"jpg",new File("out.jpg"));
}
可以发现输出的图片黑屏。
修复
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
jpg情况下,改为使用BufferedImage.TYPE_INT_RGB,即可正常显示。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。