Thumbnailator
maven导包
<!-- 图片缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
import com.ej.common.SystemConstants;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.net.HttpURLConnection;
import java.util.*;
public class PictureTool {
/**
* 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
*
* @param imgsrc 源图片地址
* @param imgdist 目标图片地址
* @param widthdist 压缩后图片宽度(当rate==null时,必传)
* @param heightdist 压缩后图片高度(当rate==null时,必传)
* @param rate 压缩比例.,当flag=true可不填
* @param flag 判断是根据rate还是尺寸来进行压缩
*/
public static void reduceImg(String imgsrc, String imgdist, int widthdist,
int heightdist, Float rate, boolean flag) {
try {
File srcfile = new File(imgsrc);
// 检查文件是否存在
if (!srcfile.exists()) {
log.info("======================文件路径不存在:" + imgsrc);
return;
}
if (flag) { //true时按照尺寸大小来进行压缩
int[] results = getImgWidth(srcfile);
if (results == null || results[0] == 0 || results[1] == 0) {
return;
} else {
widthdist = results[0];
heightdist = results[1];
if (widthdist < 200) { //判断图片的尺寸是否超过200,是否需要进行压缩
copyFile(imgsrc, imgdist);
}
DecimalFormat df = new DecimalFormat("0.00");
rate = Float.parseFloat(df.format(200.0 / widthdist));
widthdist = (int) (widthdist * rate);
heightdist = (int) (heightdist * rate);
}
} else {
// 如果rate不为空说明是按比例压缩
if (rate != null && rate > 0) {
// 获取文件高度和宽度
int[] results = getImgWidth(srcfile);
if (results == null || results[0] == 0 || results[1] == 0) {
return;
} else {
widthdist = (int) (results[0] * rate);
heightdist = (int) (results[1] * rate);
}
}
}
// 开始读取文件并进行压缩
Image src = javax.imageio.ImageIO.read(srcfile);
BufferedImage tag = new BufferedImage((int) widthdist,
(int) heightdist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
src.getScaledInstance(widthdist, heightdist,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 获取图片宽度
*
* @param file 图片文件
* @return 宽度
*/
public static int[] getImgWidth(File file) {
InputStream is = null;
BufferedImage src = null;
int result[] = {0, 0};
try {
is = new FileInputStream(file);
src = javax.imageio.ImageIO.read(is);
result[0] = src.getWidth(null); // 得到源图宽
result[1] = src.getHeight(null); // 得到源图高
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 复制单个文件
*
* @param oldPath 原文件路径 如:D:\\work\\32.jpg
* @param newPath 复制后路径 如:D:\\work\\33.jpg
*/
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
log.info("======================复制单个文件操作出错:---旧路径:" + oldPath + "\t\t新路径:" + newPath);
e.printStackTrace();
}
}
/**
* 流图片保存与压缩
*
* @param file 流
* @param fileName 原图片路径
* @param compress 压缩后图片路径
* @throws IOException
*/
public static void imageCompress(MultipartFile file, String fileName, String compress) {
String filePath = SystemConstants.projectRealPath + fileName;
String filePath_compress = SystemConstants.projectRealPath + compress; //压缩后路径
File saveDir = new File(filePath);
if (!saveDir.getParentFile().exists()) {
saveDir.getParentFile().mkdirs();
}
try {
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.5f).toFile(saveDir);
} catch (IOException e) {
e.printStackTrace();
}
reduceImg(filePath, filePath_compress, 0, 0, 0.4f, false);
}
/**
* 根据链接下载图片
* @param urlPath 图片链接
* @param path 本地地址
*/
public static void downloadPicture(String urlPath,String path){
URL url = null;
try {
url = new URL(urlPath);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 本地图片转换成base64字符串
* @param imgUrl图片本地路径
* @return base64字符串
*/
public static String ImageToBase64ByLocal(String imgUrl) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgUrl);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* 在线图片转换成base64字符串
* @param imgUrl图片线上路径
*/
public static String ImageToBase64ByOnline(String imgUrl) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(imgUrl);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray());
}
/**
* base64字符串转换成图片
* @param imgStr base64字符串
* @param imgUrl图片存放路径
*/
public static boolean Base64ToImage(String imgStr,String imgUrl) { // 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null || imgStr.equals("")) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgUrl);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}