图片等比压缩

图片处理工具类

对图片进行等比压缩,或者指定宽高压缩

package com.aerors.Utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * 
 * @Description 图片处理工具类
 * @author chenchen
 * @Date 2017年11月7日 下午2:40:06
 * @version 1.0.0
 */
public class ImageThumb {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String imagePath = "D:\\Koala.jpg";  
        String outPath = "D:\\5";
        scaleImage(imagePath,0.1f,outPath);
        setSize(imagePath,outPath,300,200);
        setSuffix(imagePath,outPath,"png");
    }

    /**
     * 
     * @Description 改变图片格式
     * @author chenchen
     * @Date 2017年11月7日 下午2:26:45
     * @param 图片路径、输出路径、图片格式
     * @throws IOException 
     */
    public static void setSuffix(String imagePath, String outPath, String suffix) throws IOException {
        // TODO Auto-generated method stub
        BufferedImage image = ImageIO.read(new File(imagePath));  
        Builder builder = null;  
        builder = Thumbnails.of(image).scale(1f);
        builder.outputFormat(suffix).toFile(outPath); 
        System.out.println("压缩成功");
    }


    /**
     * 
     * @Description 图片按比例压缩
     * @author chenchen
     * @Date 2017年11月7日 下午2:11:12
     * @param 图片路径、压缩比例、输出路径
     */
    public static void scaleImage(String imagePath,double num,String outImage) throws IOException{
        BufferedImage image = ImageIO.read(new File(imagePath));  
        Builder builder = null;  
        builder = Thumbnails.of(image).scale(num);
        builder.outputFormat("jpg").toFile(outImage); 
        System.out.println("压缩成功");
    }

    /**
     * 
     * @Description 指定图片压缩大小
     * @author chenchen
     * @Date 2017年11月7日 下午2:16:47
     * @param 图片路径、输出路径、指定压缩后图片的宽、高
     * 
     */
    public static void setSize(String imagePath,String outPath,int width,int height) throws IOException{
        BufferedImage image = ImageIO.read(new File(imagePath));  
        Builder builder = null;  

        int imageWidth = image.getWidth();  
        int imageHeitht = image.getHeight();  
        if ((float)height / width != (float)imageWidth / imageHeitht) {  
            if (imageWidth > imageHeitht) {  
                image = Thumbnails.of(imagePath).height(height).asBufferedImage();  
            } else {  
                image = Thumbnails.of(imagePath).width(width).asBufferedImage();  
            }  
            builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, width, height).size(width, height);  
        } else {  
            builder = Thumbnails.of(image).size(width, height);  
        }  
        builder.outputFormat("jpg").toFile(outPath);

        System.out.println("压缩成功");
    }

}

你可能感兴趣的:(Java)