codehello

图片压缩技术

jar引入:http://mvnrepository.com/artifact/net.coobird/thumbnailator/0.4.8

<!--pic-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>


Java生成缩略图Thumbnailator

案例1:通过google插件Thumbnails实现图片指定大小压缩

代码功能:

1、指定源文件路径、目标文件路径、最大图片大小(单位kb)、递归压缩的比率(0-1之间,建议0.8),如果测试出现java OutOfMemoryError,大多是递归压缩比例设置有问题;

2、可以实现图片格式之间的互转,只需在源文件和目标文件路径指定即可;

3、通过测试可知,png转jpg图片占存大小变小,jgp转png图片占存大小变大;

package com.aimai.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.mysql.fabric.Response;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.name.Rename;

public class PicUtils {
    /****
     * outputFormat:输出的图片格式 outputQuality:输出的图片质量,范围:0.0~1.0,1为最高质量
     * 
     * @param args
     */

    public static void main(String[] args) {
        // PicUtils.commpressPicForScale("C:\\Users\\Administrator\\Desktop\\pic\\微信图片_20171031175302.gif",
        // "F:\\1.jpg", 500,0.8);//图片小于500kb
        try {
            /***
             * 图片尺寸不变,修改图片文件类型
             */
            // Thumbnails.of("F:\\1.jpg").scale(1f).outputFormat("png").toFile("F:\\1");
            /***
             * 图片尺寸不变,改变图片大小 。
             */
            // Thumbnails.of("F:\\2.jpg").scale(1f).outputQuality(0.25f).outputFormat("jpg").toFile("F:\\output\\2.jpg");
            /***
             * 压缩至指定图片尺寸(例如:横400高300),不保持图片比例
             */
            // Thumbnails.of("F:\\2.jpg").forceSize(200, 300).toFile("F:\\output\\2.jpg");
            /***
             * 不按照比例,指定大小进行缩放 keepAspectRatio(false)默认是按照比例缩放的
             */
            // Thumbnails.of("F:\\2.jpg").size(200,
            // 200).keepAspectRatio(false).toFile("F:\\2_200x200.jpg");
            /***
             * 单个图片等比例缩放 3.0是一个double类型的数字,缩放比例,大于1就是变大,小于1就是缩小
             */
            // File file=new File("F:\\2.jpg");
            // Thumbnails.of(new FileInputStream(file)).scale(3.0).toFile(new
            // File("F:\\4.jpg"));
            /***
             * 批量生产缩略图,将文件夹下图片生成相应的缩略图
             */
            // Thumbnails.of(new
            // File("F:\\output").listFiles()).scale(0.2).outputFormat("jpg").toFiles(Rename.PREFIX_DOT_THUMBNAIL);
            /***
             * 给图片加水印 fromPic是原图,waterPic是水印图片,toPic是生成后的图片 watermark(位置,水印图,透明度)
             */
            // Thumbnails.of("F:\\2.jpg").scale(0.8).watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new
            // File("F:\\2.jpg")),0.5f).outputQuality(0.8f).toFile("F:\\2.jpg");
            /****
             * 旋转图片rotate(角度),正数:顺时针 负数:逆时针
             */
            // Thumbnails.of("F:\\2.jpg").scale(0.5).rotate(-90).toFile("F:\\2.jpg");
            /***
             * 裁剪图片
             */
            // Thumbnails.of("F:\\2.jpg").sourceRegion(Positions.CENTER,
            // 300,300).scale(1.0).toFile("F:\\2.jpg");
            // 图片中心400x400的区域
            // Thumbnails.of("F:\\2.jpg").sourceRegion(Positions.CENTER, 400,400).size(200,
            // 200).keepAspectRatio(false).toFile("F:\\center_200x200.jpg");
            // 图片右下角400x400区域
            // Thumbnails.of("F:\\2.jpg").sourceRegion(Positions.BOTTOM_RIGHT,
            // 400,400).size(200,
            // 200).keepAspectRatio(false).toFile("F:\\buttomRigth_200x200.jpg");
            // 指定坐标
            // Thumbnails.of("F:\\2.jpg").sourceRegion(600, 500, 400, 400).size(200,
            // 200).keepAspectRatio(false).toFile("F:\\point_200x200.jpg");
            /***
             * web输出流图片,以outputstream输出流的方式response给浏览器去展示
             */
            // Thumbnails.of(new
            // File("F:\\2.jpg")).scale(0.5).outputQuality(0.1).toOutputStream(response.getOutputStream());
            /***
             * 输出到BufferedImage
             */
            BufferedImage thumbnail = Thumbnails.of("F:\\2.jpg").size(1280, 1024).asBufferedImage();
            ImageIO.write(thumbnail, "jpg", new File("F:\\buffImage.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据指定大小和指定精度压缩图片
     * 
     * @param srcPath
     *            源图片地址
     * @param desPath
     *            目标图片地址
     * @param desFilesize
     *            指定图片大小,单位kb
     * @param accuracy
     *            精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static String commpressPicForScale(String srcPath, String desPath, long desFileSize, double accuracy) {
        if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(srcPath)) {
            return null;
        }
        if (!new File(srcPath).exists()) {
            return null;
        }
        try {
            File srcFile = new File(srcPath);
            long srcFileSize = srcFile.length();
            System.out.println("源图片:" + srcPath + ",大小:" + srcFileSize / 1024 + "kb");

            // 1、先转换成jpg
            Thumbnails.of(srcPath).scale(1f).toFile(desPath);
            // 递归压缩,直到目标文件大小小于desFileSize
            commpressPicCycle(desPath, desFileSize, accuracy);

            File desFile = new File(desPath);
            System.out.println("目标图片:" + desPath + ",大小" + desFile.length() / 1024 + "kb");
            System.out.println("图片压缩完成!");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return desPath;
    }

    private static void commpressPicCycle(String desPath, long desFileSize, double accuracy) throws IOException {
        File srcFileJPG = new File(desPath);
        long srcFileSizeJPG = srcFileJPG.length();
        // 2、判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
            return;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(srcFileJPG);
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(new BigDecimal(accuracy)).intValue();

        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        commpressPicCycle(desPath, desFileSize, accuracy);
    }
}

 

参考文献:http://rensanning.iteye.com/blog/1545708

分类:

技术点:

相关文章: