ImageIO 先read再write 文件变小了

ImageIO 先read再write 图片文件变小了以及处理办法:

public static void testImageIo(){
     
        try {
     
            InputStream inputStream =  FileUtils.openInputStream(new File("/Users/mac/Desktop/B612/a.jpg"));
            BufferedImage bImage = ImageIO.read(inputStream);
            // 此处直接write会导致图片被压缩处理,失真
//            ImageIO.write(bImage,"jpg",new File("/Users/mac/Desktop/B612/a-copy.jpg"));

            // 所以经过以下处理,可以调整相应的参数,甚至可以生成大于原图的图片
            Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
            if (iter.hasNext()) {
     
                ImageWriter writer = iter.next();
                ImageWriteParam param = writer.getDefaultWriteParam();

                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                // 该参数在0.92~0.93左右是最接近原图大小的,最大是1
                param.setCompressionQuality(0.92f);
                FileImageOutputStream out = new FileImageOutputStream(new File(
                        "/Users/mac/Desktop/B612/a-copy01.jpg"));
                writer.setOutput(out);
                // writer.write(bi);
                writer.write(null, new IIOImage(bImage, null, null), param);
                out.close();
                writer.dispose();
            }
        }catch (Exception e){
     
            e.printStackTrace();
        }
    }

参考:https://www.iteye.com/problems/72994
https://blog.csdn.net/liuxiaoshuang002/article/details/89680313

你可能感兴趣的:(java基础,ImageIO)