java圖片壓縮和剪裁示例

/*
 * Copyright 2013 NingPai, Inc. All rights reserved.
 * NINGPAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package co.dc.main.util;

import java.awt.Image;
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.util.Arrays;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 單個圖片上傳Util方法
 * @author zhangpeng
 */
public class UploadImage {
	
    /*
     *以下是圖片縮放的方法 
     */
    
	public Image img; 
	public File donefile;
    public int width;  
    public int height;
	
    public UploadImage() {
        // TODO Auto-generated constructor stub
    }
    /**
     * 上傳圖片
     * @param uploadForm
     * @param request
     * @return imageurl
     */
        public String uploadImage(FileUploadForm uploadForm,
                HttpServletRequest request,MultipartFile mFile,String urlpath){
        // 存儲圖片路徑
        String imageurl = "";
        if (mFile != null && mFile.getSize() != 0) {
            // 獲取系統時間
            long now = System.currentTimeMillis();
            // 根據系統時間生成上傳後保存的文件名
            String prefix = String.valueOf(now);
            // 保存圖片路徑
            String picPath = urlpath+"/";
            // 根據真實路徑創建目錄文件
//            File picSaveFile = new File(picPath);
//            if (!picSaveFile.exists()) {
//                picSaveFile.mkdirs();
//            }
            // 文件的後綴
            String fileNamess = picPath + prefix + ".jpg";
            imageurl = "photos/"+prefix;
            File file = new File(fileNamess);
            try {
                mFile.transferTo(file);
                donefile = new File(fileNamess);// 讀入文件  
                img = ImageIO.read(donefile);      // 構造Image對象  
                width = img.getWidth(null);    // 得到源圖寬  
                height = img.getHeight(null);  // 得到源圖長 
                resizeFix(994, 830,picPath + prefix+"_1000.jpg");
                resizeFix2(2400, 1650,picPath + prefix+"_250.jpg");
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
        return imageurl+","+width+","+height;
        }
        
        /** 
         * 按照寬度還是高度進行【壓縮】 
         * @param w int 最大寬度 
         * @param h int 最大高度 
         */  
        public void resizeFix(int w, int h,String newfileurl) throws IOException {
        	int h2 = 0,w2 = 0;
            if (width > w) {
            	h2 = (int)(height * w / width);
                if(h2 > h){
                	w2 = (int) (w * h / h2);
                	//System.out.println(w2+"=="+h);
                	resize1(w2, h,newfileurl);
                }else{
                	//System.out.println(w+"=="+h2);
                	resize1(w, h2,newfileurl);
                }
            }else if(height > h){
            	w2 = (int) (width * h / height);
            	//System.out.println(w2+"=="+h);
            	resize1(w2, h,newfileurl);
            }else{
            	//System.out.println(width+"=="+height);
            	resize1(width, height,newfileurl);
            }
        }  
        
        /** 
         * 按照寬度還是高度進行【裁剪 】
         * @param w int 最大寬度 
         * @param h int 最大高度 
         */  
        public void resizeFix2(int w, int h,String newfileurl) throws IOException {
            if (width > w && height > h) {
            	cutImage(donefile, new File(newfileurl), w, h);
            }else if(width > w && height <= h){
            	cutImage(donefile, new File(newfileurl), w, height);
            }else if(width <= w && height > h){
            	cutImage(donefile, new File(newfileurl), width, h);
            }else{
            	cutImage(donefile, new File(newfileurl), width, height);
            }
        }
        
        /** 
         * 強制壓縮/放大圖片到固定的大小 
         * @param w int 新寬度 
         * @param h int 新高度 
         */  
        public void resize1(int w, int h,String newfileurl) throws IOException {  
            // SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優先級比速度高 生成的圖片質量比較好 但速度慢  
            BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );   
            image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪製縮小後的圖  
            File destFile = new File(newfileurl);  
            FileOutputStream out = new FileOutputStream(destFile); // 輸出到文件流  
            // 可以正常實現bmp、png、gif轉jpg
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            encoder.encode(image); // JPEG編碼  
            out.close(); 
        }
        
        /**
         * <p>Title: cutImage</p>
         * <p>Description:  根據原圖與裁切size截取局部圖片</p>
         * @param srcImg    源圖片
         * @param output    圖片輸出流
         * @param rect        需要截取部分的座標和大小
         */
        public void cutImage(File srcImg, File output,int w, int h){
        	java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, w, h);
            if(srcImg.exists()){
                java.io.FileInputStream fis = null;
                ImageInputStream iis = null;
                try {
                    fis = new FileInputStream(srcImg);
                    // ImageIO 支持的圖片類型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                    String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                    String suffix = null;
                    // 獲取圖片後綴
                    if(srcImg.getName().indexOf(".") > -1) {
                        suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                    }// 類型和圖片後綴全部小寫,然後判斷後綴是否合法
                    if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
                        return ;
                    }
                    // 將FileInputStream 轉換爲ImageInputStream
                    iis = ImageIO.createImageInputStream(fis);
                    // 根據圖片類型獲取該種類型的ImageReader
                    ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
                    reader.setInput(iis,true);
                    ImageReadParam param = reader.getDefaultReadParam();
                    param.setSourceRegion(rect);
                    BufferedImage bi = reader.read(0, param);
                    ImageIO.write(bi, suffix, output);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if(fis != null) fis.close();
                        if(iis != null) iis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else {
            }
        }

//        public static void main(String[] args) {
//        	width = 1500;
//        	height = 1800;
//        	try {
//				resizeFix(241, 165, "");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章