17.3.27 图片压缩教程

2017-03-23  本文已影响59人  薛定谔的猴子

有时候上传图片的时候,文件太大,等到要加载的时候,因为体积太大而加载速度变慢,同时也会占用服务器的空间,因此图片的压缩就很有必要了

以下这个工具类是公共类,可直接使用
链接下载

链接:http://pan.baidu.com/s/1geLNgCr 密码:hf9j
import java.awt.Image;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import javax.imageio.ImageIO;  
  
import com.sun.image.codec.jpeg.JPEGCodec;  
import com.sun.image.codec.jpeg.JPEGEncodeParam;  
import com.sun.image.codec.jpeg.JPEGImageEncoder;  


public class Picture {
    /** 
     * 等比例压缩图片文件<br> 先保存原文件,再压缩、上传 
     * @param oldFile  要进行压缩的文件 
     * @param newFile  新文件 
     * @param width  宽度 //设置宽度时(高度传入0,等比例缩放) 
     * @param height 高度 //设置高度时(宽度传入0,等比例缩放) 
     * @param quality 质量 
     * @return 返回压缩后的文件的全路径 
     * @throws Exception 
     */  
    public static String zipImageFile(File oldFile,File newFile, int width, int height,  
            float quality) throws Exception {  
        
         if (oldFile == null) {  
             return null;  
         }  
         String newImage = null;  
         try {  
             /** 对服务器上的临时文件进行处理 */  
             Image srcFile = ImageIO.read(oldFile);  
             int w = srcFile.getWidth(null);  
         //  System.out.println(w);  
             int h = srcFile.getHeight(null);  
         //  System.out.println(h);  
   
             /** 宽,高设定 */  
             BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
             tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);  
             //String filePrex = oldFile.substring(0, oldFile.indexOf('.'));  
             /** 压缩后的文件名 */  
             //newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length());  
   
             /** 压缩之后临时存放位置 */  
             FileOutputStream out = new FileOutputStream(newFile);  
   
             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
             JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);  
             /** 压缩质量 */  
             jep.setQuality(quality, true);  
             encoder.encode(tag, jep);  
             out.close();  
         } catch (FileNotFoundException e) {  
             e.printStackTrace();  
         } catch (IOException e) {  
             e.printStackTrace();  
         }  
         return newImage;  
    
    }  
    public static void main(String[] args) throws Exception {
         // System.out.println(Picture.zipImageFile(new File("E:/a.jpg"),new File("E:/a2.jpg"),250, 250, 50f));  
    }

}

压缩前后对比

压缩前
压缩后
上一篇 下一篇

猜你喜欢

热点阅读