JAVA 裁剪 壓縮圖片 工具類

JAVA 裁剪 壓縮圖片 工具類


這是一個工具類,直接上代碼吧。

package demo01;

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;

import java.awt.Graphics;
import java.awt.image.BufferedImage;  
import java.util.HashMap;  
import java.util.List;  
import java.util.ArrayList;  
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;  
import java.util.Map;  


/**
 * 壓縮 圖片工具類
 * @author yangnuo
 *
 */
public class ResizeImg {
	
	
	/**
	 * 裁剪圖片
	 * @param image
	 * @param w
	 * @param h
	 * @throws IOException
	 */
    public void cutImage(File image, int w, int h) throws IOException {
        
        // 判斷參數是否合法 
        if (null == image || 0 == w || 0 == h) {
            new Exception ("哎呀,截圖出錯!!!");
        }
        
        /*InputStream inputStream = new FileInputStream(image);
        // 用ImageIO讀取字節流   
        BufferedImage bufferedImage = ImageIO.read(inputStream);   
        BufferedImage distin = null;   
        // 返回源圖片的寬度。   
        int srcW = bufferedImage.getWidth();   
        // 返回源圖片的高度。   
        int srcH = bufferedImage.getHeight();   
        int x = 0, y = 0;   
        // 使截圖區域居中   
        x = srcW / 2 - w / 2;
        y = srcH / 2 - h / 2;
        srcW = srcW / 2 + w / 2;   
        srcH = srcH / 2 + h / 2;   
        // 生成圖片   
        distin = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = distin.getGraphics();
        g.drawImage(bufferedImage, 0, 0, w, h, x, y, srcW, srcH, null);*/
        
        InputStream inputStream = new FileInputStream(image);
        // 用ImageIO讀取字節流   
        BufferedImage bufferedImage = ImageIO.read(inputStream);   
        BufferedImage distin = null;   
        // 返回源圖片的寬度。   
        int srcW = bufferedImage.getWidth();   
        // 返回源圖片的高度。   
        int srcH = bufferedImage.getHeight();
        
        
        System.out.println(srcW+"   "+srcH);
        
        // 生成圖片   
        distin = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = distin.getGraphics();
        
//      g.drawImage(bufferedImage, srcW/3, srcH/3, null);
        g.drawImage(bufferedImage, 0, 0, srcW/3, srcH/3, srcW/3, srcH/3, srcW, srcH, null);
        
        ImageIO.write(distin, "jpg", new File("E:/"+(int)(Math.random()*1000)+image.getName()));
    }
	
	
	
	
	
  
    /** 
     * @param im            原始圖像 
     * @param resizeTimes   需要縮小的倍數,縮小2倍爲原來的1/2 ,這個數值越大,返回的圖片越小 
     * @return              返回處理後的圖像 
     */  
    public BufferedImage resizeImage(BufferedImage im, float resizeTimes) {
        /*原始圖像的寬度和高度*/
        int width = im.getWidth();
        int height = im.getHeight();

        /*調整後的圖片的寬度和高度*/  
        int toWidth = (int) (Float.parseFloat(String.valueOf(width)) / resizeTimes);
        int toHeight = (int) (Float.parseFloat(String.valueOf(height)) / resizeTimes);

        /*新生成結果圖片*/
        BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);

        result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return result;
    }  
  
    /** 
     * @param im            原始圖像 
     * @param resizeTimes   倍數,比如0.5就是縮小一半,0.98等等double類型 
     * @return              返回處理後的圖像 
     */
    public BufferedImage zoomImage(BufferedImage im) {
        
        /*調整後的圖片的寬度和高度*/
        int toWidth=64;
        int toHeight=64;
        
        /*原始圖像的寬度和高度  百分比縮略*/
        toHeight = im.getHeight()/50;
        toWidth = im.getWidth()/50;
        
        
        /*新生成結果圖片*/
        BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);

        result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return result;
    }
  
    /** 
     * @param path  要轉化的圖像的文件夾,就是存放圖像的文件夾路徑 
     * @param type  圖片的後綴名組成的數組 
     * @return 
    */  
    public List<BufferedImage> getImageList(String path, String[] type) throws IOException{
        Map<String,Boolean> map = new HashMap<String, Boolean>();
        for(String s : type) {
            map.put(s,true);
        }
        List<BufferedImage> result = new ArrayList<BufferedImage>();
        File[] fileList = new File(path).listFiles();
        for (File f : fileList) {
            if(f.length() == 0)
                continue;
            if(map.get(getExtension(f.getName())) == null)
                continue;
            result.add(javax.imageio.ImageIO.read(f));
        }
        return result;
    }  
    public BufferedImage getImage(String path) throws IOException{
        return javax.imageio.ImageIO.read(new File(path));
    }  
  
    /** 
     * 把圖片寫到磁盤上 
      * @param im 
     * @param path     eg: C://home// 圖片寫入的文件夾地址 
      * @param fileName DCM1987.jpg  寫入圖片的名字 
      * @return 
     */  
    public boolean writeToDisk(BufferedImage im, String path, String fileName) {
        File f = new File(path + fileName);
        String fileType = getExtension(fileName);
        if (fileType == null)
            return false;
        try {
            ImageIO.write(im, fileType, f);
            im.flush();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
  
  
    public boolean writeHighQuality(BufferedImage im, String fileFullPath) {
        try {
            /*輸出到文件流*/
            FileOutputStream newimage = new FileOutputStream(fileFullPath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
            /* 壓縮質量 */
            jep.setQuality(1f, true);
            encoder.encode(im, jep);
           /*近JPEG編碼*/
            newimage.close();
            return true;
        } catch (Exception e) {
            return false;
        }  
    }  
  
    /** 
     * 返回文件的文件後綴名 
      * @param fileName 
      * @return 
    */  
    public String getExtension(String fileName) {
        try {
            return fileName.split("\\.")[fileName.split("\\.").length - 1];
        } catch (Exception e) {
            return null;
        }
    }

    
    /**
     * 測試方法
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{
  
    	ResizeImg r=new ResizeImg();
        String filepath="E:\\";
        String filename="001.jpg";
        
        //裁剪圖片
//        r.cutImage(new File(filepath+filename), 1000, 1000);
        
        //壓縮圖片
        BufferedImage im=r.getImage(filepath+filename);  
        r.writeHighQuality(r.zoomImage(im), filepath+"s_"+filename);//爲防止覆蓋原圖片,加s_區分是壓縮以後的圖片 
    }
} 



其中 cutImage()  方法用於裁剪圖片,這裏我寫了兩種,一種自定義的(被註釋了),還有一種是截取圖片大致中間的部分。剩餘的是壓縮圖片的方法,zoomImage()的方法中可以指定壓縮圖片的大小。測試方法也給出了,在工具類的最底部。



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