<!--图片压缩-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.7</version>
</dependency>
package com.springboot.demo.utils;/**
* @author Mr伍
* @date 2020/4/3 17:17
*/
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImgZipBatchUtil {
/**
*需要压缩的文件的父文件夹绝对路径
*/
private static String absolutePath;
/**
* 需要压缩后文件的上限单位KB
*/
private static Long fileSize;
public ImgZipBatchUtil () {
Prop prop = PropKit.use("config.properties");
String rootPath= prop.get("ImagfileZipRootPath");
Long ImagfileZipSize= prop.getLong("ImagfileZipSize");
//absolutePath=rootPath;
absolutePath="D:\\workoffice\\work\\WXWork\\1688851781973394\\Cache\\File\\2021-07\\72015911杜合权";
fileSize=ImagfileZipSize;
}
/**
* 启动程序 将此路径下的图片全部压缩
* 批量压缩图片大概一秒压缩一张图片
*/
public void start() {
File file=new File(absolutePath);
Long stat=System.currentTimeMillis();
//按文件大小需求压缩
//traversalImage(file);
try {
//将文件夹内文件压缩必须在最后一个文件夹
Thumbnails.of(new File(absolutePath).listFiles()).scale(0.5).outputQuality(0.8f)
.toFiles(Rename.NO_CHANGE);
} catch (IOException e) {
e.printStackTrace();
}
Long end =System.currentTimeMillis()-stat;
System.err.println("耗时:"+end);
}
/**
* 给一个文件夹遍历出所有文件及文件夹路径
* @param file
*/
public void traversalImage(File file) { // 给一个文件夹路径
File[] files = file.listFiles();
// 获取文件夹下面的所有文件
for (File f : files) {
// 判断是否为文件夹
if (f.isDirectory()) {
System.err.println("这是文件夹----" + f.getAbsolutePath()+ "-------------");
// 如果是文件夹,重新遍历
traversalImage(f);
//此处需要遍历查找此文件夹下是否有还有文件夹,没有就压缩
/* try {
//将文件夹内文件压缩必须在最后一个文件夹
Thumbnails.of(new File(absolutePath).listFiles()).scale(0.5).outputQuality(0.8f)
.toFiles(Rename.NO_CHANGE);
} catch (IOException e) {
e.printStackTrace();
}*/
} else {
// 如果是文件 获取文件路径
String allPath=f.getAbsolutePath();
log.debug(String.format(" %s;文件大小为:%s B",allPath,f.length()));
zipImg(allPath);
}
}
}
/**
* 原路径压缩
* @param absolutePath
*/
public void zipImg(String absolutePath){
// String suffix = absolutePath.substring(absolutePath.lastIndexOf(".") + 1);
// String prefix = absolutePath.substring(0, absolutePath.lastIndexOf("."));
File file=new File(absolutePath);
if(file==null||!file.isFile()){
log.error(absolutePath+"不是一个文件");
return;
}
byte[] bytes=File2byte(file);
try {
log.info("原文件大小:"+bytes.length);
while (bytes.length>fileSize*1024){
System.err.println(bytes.length);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
//Thumbnails允许通过传入文件名、文件、网络图的URL、图片流、图片缓存多种方式来初始化构造器。
//scale参数 0.1f 12s,0.5f 12s,0.7f 19s,0.9f 55s,
// outputQuality参数0.8为最佳耗时质量
Thumbnails.of(inputStream).scale(0.5f)
.outputQuality(0.8f)
//.outputFormat(suffix) 输出格式后缀
// .toFile(prefix); 输出位置不带后缀
.toOutputStream(outputStream);
bytes=outputStream.toByteArray();
}
log.debug(String.format("压缩后的大小: %s B:",bytes.length));
byteToFile(bytes,absolutePath);
} catch (IOException e) {
log.error(absolutePath);
log.error(e);
e.printStackTrace();
}
}
/**
* 将文件转换成byte数组
* @param
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return buffer;
}
/**
* byte[] 转 file
* @param bytes
* @param path
* @return
* @see [类、类#方法、类#成员]
*/
public static void byteToFile(byte[] bytes, String path)
{
try
{
// 根据绝对路径初始化文件
File localFile = new File(path);
if (!localFile.exists())
{
localFile.createNewFile();
}
// 输出流
OutputStream os = new FileOutputStream(localFile);
os.write(bytes);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//图片压缩 github上面的地址是:https://github.com/coobird/thumbnailator
// scale是可以指定图片的大小,值在0到1之间,1f就是原图大小,0.5就是原图的一半大小,
// 这里的大小是指图片的长宽可以有两个参数设置宽高。
//outputQuality是图片的质量,值也是在0到1,越接近于1质量越好,越接近于0质量越差,0.8效果最好时间最优。
Thumbnails.of("C:\\Users\\DELL\\Desktop\\0024-产权证-04.JPG")
.scale(0.1f)
.outputQuality(1f).outputFormat("jpg")
.toFile("E:\\ftp\\ftpFile\\3-2-1927");
//AffineTransform此类也可以
//批量产生缩略图
/* Thumbnails.of(new File("D:\\pics").listFiles()).scale(0.2).outputFormat("png")
.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
旋转图片
Thumbnails.of(fromPic).scale(0.5).rotate(90).toFile(toPic);
//给图片加水印 fromPic是原图,waterPic是水印图片,toPic是生成后的图片
Thumbnails.of(fromPic)
.scale(0.8)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(waterPic), 0.5f)
.outputQuality(0.8f).toFile(toPic);
*/
//zipWidthHeightImageFile(new File("E:\\ftp\\ftpFile\\201994\\中文.jpeg"), new File("E:\\ftp\\ftpFile\\3-2.png"), 600, 400, 1f);
// zipImageFile(new File("E:\\ftp\\ftpFile\\201994\\中文.jpeg"), new File("E:\\ftp\\ftpFile\\3-2.png"), 600, 400, 0.5f);
//zipImageFile(new File("C:\\spider\\3.jpg"),new File("C:\\spider\\3-3.jpg"),425,638,0.7f);
System.out.println("ok");
}catch (Exception e){
System.err.println("文件没有找到"+e.getClass().getName()+":"+e.getMessage());
}
}
/**
* 根据设置的宽高等比例压缩图片文件<br> 先保存原文件,再压缩、上传
* @param oldFile 要进行压缩的文件
* @param newFile 新文件
* @param width 宽度 //设置宽度时(高度传入0,等比例缩放)
* @param height 高度 //设置高度时(宽度传入0,等比例缩放)
* @param quality 质量
* @return 返回压缩后的文件的全路径
*/
public static String zipImageFile(File oldFile,File newFile, int width, int height,float quality) {
if (oldFile == null) {
return null;
}
try {
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(oldFile);
int w = srcFile.getWidth(null);
int h = srcFile.getHeight(null);
double bili;
if(width>0){
bili=width/(double)w;
height = (int) (h*bili);
}else{
if(height>0){
bili=height/(double)h;
width = (int) (w*bili);
}
}
String srcImgPath = newFile.getAbsoluteFile().toString();
System.out.println(srcImgPath);
String subfix = "jpg";
subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1,srcImgPath.length());
BufferedImage buffImg = null;
if(subfix.equals("png")){
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}else{
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
Graphics2D graphics = buffImg.createGraphics();
graphics.setBackground(new Color(255,255,255));
graphics.setColor(new Color(255,255,255));
graphics.fillRect(0, 0, width, height);
graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(buffImg, subfix, new File(srcImgPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newFile.getAbsolutePath();
}
/**
* 按设置的宽度高度压缩图片文件<br> 先保存原文件,再压缩、上传
* @param oldFile 要进行压缩的文件全路径
* @param newFile 新文件
* @param width 宽度
* @param height 高度
* @param quality 质量
* @return 返回压缩后的文件的全路径
*/
public static String zipWidthHeightImageFile(File oldFile,File newFile, int width, int height,float quality) {
if (oldFile == null) {
return null;
}
String newImage = null;
try {
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(oldFile);
String srcImgPath = newFile.getAbsoluteFile().toString();
System.out.println(srcImgPath);
String subfix = "jpg";
subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1,srcImgPath.length());
BufferedImage buffImg = null;
if(subfix.equals("png")){
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}else{
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
Graphics2D graphics = buffImg.createGraphics();
graphics.setBackground(new Color(255,255,255));
graphics.setColor(new Color(255,255,255));
graphics.fillRect(0, 0, width, height);
graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(buffImg, subfix, new File(srcImgPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newImage;
}
}