序
本文主要来聊一下使用ImageIO在BufferedImage.TYPE_INT_ARGB模式下操作jpg格式图片显示黑色的bug。
bug
复现实例
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,即可正常显示。