package com.example.atlogging.controller;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 图片压缩
* https://www.cnblogs.com/miskis/p/5500822.html
*/
public class UploadImg {
String fromFileStr;
String saveToFileStr;
String sysimgfile;
int width;
int height;
String suffix;
/**
* @param fromFileStr 原始图片完整路径
* @param saveToFileStr 缩略图片保存路径
* @param sysimgfile 处理后的图片名
* @param suffix 处理后的图片后缀名
* @param width 处理后的图片宽度
* @param height 处理后的图片高度
*/
public UploadImg(String fromFileStr, String saveToFileStr, String sysimgfile, String suffix, int width, int height) {
this.fromFileStr = fromFileStr;
this.saveToFileStr = saveToFileStr;
this.sysimgfile = sysimgfile;
this.width = width;
this.height = height;
this.suffix = suffix;
File saveFilePath = new File(saveToFileStr);
if (!saveFilePath.exists()) {
saveFilePath.mkdirs();
}
}
public boolean createThumbnail() throws Exception {
// fileExtNmae是图片的格式 gif JPG 或png
// String fileExtNmae="";
File F = new File(this.fromFileStr);
if (!F.isFile())
throw new Exception(F
+ " is not image file error in CreateThumbnail!");
File ThF = new File(this.saveToFileStr, this.sysimgfile + "." + this.suffix);
BufferedImage buffer = ImageIO.read(F);
/*
* 核心算法,计算图片的压缩比
*/
int w = buffer.getWidth();
int h = buffer.getHeight();
double ratiox = 0.1d;
double ratioy = 0.1d;
ratiox = w * ratiox / this.width;
ratioy = h * ratioy / this.height;
if (ratiox >= 1) {
if (ratioy < 1) {
ratiox = this.height * 1.0 / h;
} else {
if (ratiox > ratioy) {
ratiox = this.height * 1.0 / h;
} else {
ratiox = this.width * 1.0 / w;
}
}
} else {
if (ratioy < 1) {
if (ratiox > ratioy) {
ratiox = this.height * 1.0 / h;
} else {
ratiox = this.width * 1.0 / w;
}
} else {
ratiox = this.width * 1.0 / w;
}
}
/*
* 对于图片的放大或缩小倍数计算完成,ratiox大于1,则表示放大,否则表示缩小
*/
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(ratiox, ratiox), null);
buffer = op.filter(buffer, null);
//从放大的图像中心截图
buffer = buffer.getSubimage((buffer.getWidth() - this.width) / 2, (buffer.getHeight() - this.height) / 2, this.width, this.height);
try {
ImageIO.write(buffer, this.suffix, ThF);
} catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: "
+ ex.getMessage());
}
return (true);
}
public static void main(String[] args) {
UploadImg UI;
boolean ss = false;
try {
String sysimgFile = "";//new Date().getTime() + "" + (int) (Math.random() * 100000);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
sysimgFile = df.format(new Date()) + "_8M";
System.out.println(sysimgFile);
UI = new UploadImg("F:/桌面temp/ys/8M.jpg",
"F:/桌面temp/ys", sysimgFile,
"jpg",
3024,
4032);
ss = UI.createThumbnail();
if (ss) {
System.out.println("Success");
} else {
System.out.println("Error");
}
} catch (Exception e) {
System.out.print(e.toString());
}
}
}