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()的方法中可以指定压缩图片的大小。测试方法也给出了,在工具类的最底部。



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