• 使用java来压缩图片


    使用java来压缩图片,简单几句,清清爽爽

    使用0.3的压缩比得到的结果如下(从2.8M压缩到268K,且图片的清晰度看不出明显差别):

    package carlspringtest;
    
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Iterator;
    
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.stream.ImageOutputStream;
    
    /**
     * Compress JPEG File Example
     *
     * @author Krishna
     *
     */
    public class CompressJPEGFileExample {
        public static void main(String[] args) throws FileNotFoundException, IOException{
            File imageFile = new File("f:\IMG_20151219_172146.jpg");//source
            File compressedImageFile = new File("f:\compressed_file5.jpg");//result
    
            InputStream inputStream = new FileInputStream(imageFile);
            OutputStream outputStream = new FileOutputStream(compressedImageFile);
    
            float imageQuality = 0.3f;
    
            //Create the buffered image
            BufferedImage bufferedImage = ImageIO.read(inputStream);
    
            //Get image writers
            Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpg");
    
            if (!imageWriters.hasNext())
                throw new IllegalStateException("Writers Not Found!!");
    
            ImageWriter imageWriter = (ImageWriter) imageWriters.next();
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
            imageWriter.setOutput(imageOutputStream);
    
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
    
            //Set the compress quality metrics
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(imageQuality);
    
            //Created image
            imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);
    
            // close all streams
            inputStream.close();
            outputStream.close();
            imageOutputStream.close();
            imageWriter.dispose();
        }
    }
  • 相关阅读:
    vue组件系列-数字滚动组件
    重新振兴自己
    EL表达式
    org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type sette
    Struts2常用标签总结
    mybatis+strut2+spring整合总结
    hibernate的详细注解以及例子
    Struts2基于注解的Action配置
    【干货】如何通过OPC自定义接口来实现客户端数据的读取?
    即将离职,共享下我的知识库
  • 原文地址:https://www.cnblogs.com/jinhuazhe2013/p/5059461.html
Copyright © 2020-2023  润新知