图片压缩的Java实现


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.image.codec.jpeg.*;

/**
 * 图片压缩模块
 * 
 * @author Xie Zhiping
 * @date 2017年8月18日
 */
public class CompressImageUtil {

    private Logger logger = LoggerFactory.getLogger(getClass());

//     private String imgdist="D:/tempfiles/";
//     private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//     // 以当前时间作为文件名
//     String dateStr = dateFormat.format(new Date());
//     //默认将压缩后的照片存储为.jpg格式
//     private String imgName= "_afterCompress_" + dateStr + ".jpg";
//     //压缩后照片存储路径以及照片存储名
//     String imgCompressPath = imgdist + imgName;

    /**
     * 根据指定的宽、高进行压缩
     * 图片路径imgCompressPath可以指定存储的任意格式,如.jpg/.png/.bmp
     * 
     * @param imgSourcePath :压缩前图片的路径
     * @param imgCompressPath :压缩后图片的路径
     * @param widthdist :指定压缩后图片的宽
     * @param heightdist :指定压缩后图片的高
     */
    public void compressImage(String imgSourcePath, String imgCompressPath, int widthdist, int heightdist) {
        // 根据图片路径创建指定的图片文件
        File srcImage = new File(imgSourcePath);
        // 检查图片是否存在
        if (!srcImage.exists()) {
            logger.error("指定路径下不存在相应的图片!");
            return;
        }
        // 开始读取文件并进行压缩
        try {
            // 从图片路径srcImage下读取图片,并存储在Image对象中
            Image beforeCompressImage = ImageIO.read(srcImage);
            // 图片缓冲,由于为彩色图像因此将其色彩模型设置为RGB模型
            BufferedImage bufferedImage = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
            bufferedImage.getGraphics().drawImage(
                    beforeCompressImage.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
            // 图片输出流,将输出图片存储于路径imgCompressPath下
            FileOutputStream fileOutputStream = new FileOutputStream(imgCompressPath);
            // 采用JPEG图像压缩算法
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            encoder.encode(bufferedImage);
            logger.info("图片压缩成功,压缩到路径:" + imgCompressPath);
            fileOutputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    /**
     * 根据指定压缩率进行压缩
     * 图片路径imgCompressPath可以指定存储的任意格式,如.jpg/.png/.bmp
     * 
     * @param imgSourcePath :压缩前图片的路径
     * @param imgCompressPath :压缩后图片的路径
     * @param compressRate :压缩率
     */
    public void compressImage(String imgSourcePath, String imgCompressPath, Double compressRate) {
        // 根据图片路径创建指定的图片文件
        File srcImage = new File(imgSourcePath);
        // 检查图片是否存在
        if (!srcImage.exists()) {
            logger.error("指定路径下不存在相应的图片!");
            return;
        }
        // 处理压缩比率
        if (compressRate == null || compressRate < 0) {
            logger.error("图片压缩率异常!");
        } else {
            // 获取文件宽和高,results[0]为宽,result[1]为高
            int[] results = getImageSize(srcImage);
            if (results == null || results[0] == 0 || results[1] == 0) {
                logger.error("图片大小出现异常!");
                return;
            }
            // 根据指定的压缩率对图片的宽和高进行压缩
            int widthdist = (int) (results[0] * compressRate);
            int heightdist = (int) (results[1] * compressRate);
            try {
                // 从图片路径srcImage下读取图片,并存储在Image对象中
                Image beforeCompressImage = ImageIO.read(srcImage);
                // 图片缓冲,由于为彩色图像因此将其色彩模型设置为RGB模型
                BufferedImage bufferedImage = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
                bufferedImage.getGraphics().drawImage(
                        beforeCompressImage.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
                // 图片输出流,将输出图片存储于路径imgCompressPath下
                FileOutputStream fileOutputStream = new FileOutputStream(imgCompressPath);
                // 采用JPEG图像压缩算法
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
                encoder.encode(bufferedImage);
                logger.info("图片压缩成功,压缩到路径:" + imgCompressPath);
                fileOutputStream.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取指定图片的宽、高
     * 
     * @param imgFile
     * @return :图片的宽和高组成的一维二元数组
     */
    private int[] getImageSize(File imgFile) {
        InputStream inputStream = null;
        BufferedImage src = null;
        int[] result = { 0, 0 };
        try {
            inputStream = new FileInputStream(imgFile);
            src = ImageIO.read(inputStream);
            // 获取原图片的宽
            result[0] = src.getWidth(null);
            // 获取原图片的高
            result[1] = src.getHeight(null);
            inputStream.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }
//
//    // 测试
//    public static void main(String[] args) {
//        CompressImageUtil compressImageUtil = new CompressImageUtil();
//        String imgSourcePath = "H:/test.jpg";
//        String imgCompressPath = "D:/tempfiles/result.jpg";
//        long startTime = System.currentTimeMillis();
//        //compressImageUtil.compressImage(imgSourcePath,imgCompressPath,0.2);
//        compressImageUtil.compressImage(imgSourcePath, imgCompressPath, 600, 800);
//        long endTime = System.currentTimeMillis(); 
//        System.out.println("图片压缩处理时间:"+(endTime-startTime)+"ms");
//    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值