Thumbnails is Google’s open source image processing tool
1. Introduce Thumbnails into the maven project
<dependency>
<groupId >net.coobirdgroupId>
<artifactId >thumbnailatorartifactId>
<version >0.4.8version>
dependency>
Second, the key code
String filePathName = "The root path of the image that needs to be compressed";
String thumbnailFilePathName = "Picture path after compression";
double scale = 1d;//image reduction multiple (0~1),1 means keep the original size
double quality = 1d;//The quality of compression, 1 means keep the original size (default 1)
Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);
Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
Thumbnails.of(filePathName).size(400,500).toFile(thumbnailFilePathName);//Change to 400*500, follow the original image scale or zoom to a certain height of 400*
Three, Spring-boot example
package com.example.atlogging.controller;
import com.alibaba.fastjson.JSONObject;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
@RequestMapping(path = "/thumb", produces = "application/json;charset=UTF-8")
public class TestThumbnails {
/**
* @Description: Save pictures and generate thumbnails
* @param imageFile image file
* @param request request object
* @param uploadPath upload directory
* @return
*/
private static Logger log = LoggerFactory.getLogger(TestThumbnails.class);
@RequestMapping("/up")
public String testThumb(MultipartFile imageFile, HttpServletRequest request) {
String res = this.uploadFileAndCreateThumbnail(imageFile, request, "") ;
return res;
}
public static String uploadFileAndCreateThumbnail(MultipartFile imageFile, HttpServletRequest request, String uploadPath) {
JSONObject result = new JSONObject();
int maxWidth = 1200;//Maximum width of compressed image
if (imageFile == null) {
result.put("msg", "imageFile cannot be empty");
return result.toJSONString();
}
if (imageFile.getSize() >= 10 * 1024 * 1024 ) {
result.put("msg", "The file cannot be larger than 10M");
return result.toJSONString();
}
String uuid = UUID.randomUUID().toString();
String fileDirectory = new SimpleDateFormat("yyyyMMdd").format(new Date());//Set the date format
//Mosaic background file name
String pathName = fileDirectory + File.separator + uuid + "."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//Build and save file path
//Modify the upload path to the server
String realPath = "F:/desktoptemp/ys";//request.getServletContext ().getRealPath("uploadPath");
//Get the server absolute path linux server address Get the current configuration File configuration
//String urlString=PropertiesUtil.getInstance().getSysPro(" uploadPath");
//Mosaic file path
String filePathName = realPath + File.separator + pathName;
log.info("Picture upload path:" + filePathName);
// Determine whether the file save exists
File file = new File(filePathName);
if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
//Create file
file.getParentFile().mkdirs();
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = imageFile.getInputStream();
fileOutputStream = new FileOutputStream(file);
//Write out the file
// IOUtils.copy(inputStream, fileOutputStream);
byte[] buffer = new byte[2048];
IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
buffer = null;
} catch (IOException e) {
filePathName = null;
result.put("msg", "The operation failed");
return result.toJSONString();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
result.put("msg", "The operation failed");
return result.toJSONString();
}
}
//Mosaic background file name
String thumbnailPathName = fileDirectory + File.separator + uuid + "small."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
if (thumbnailPathName.contains(".png")) {
thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
}
long size = imageFile.getSize();
double scale = 1d;
double quality = 1d;
if (size >= 200 * 1024) {// span>Compress when the image exceeds 200kb
if (size> 0) {
quality = (200 * 1024f) / size;
}
}
//Picture information
double width = 0;
double height = 0;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile.getInputStream()); //Get image stream
if (bufferedImage == null) {
// It proves that the uploaded file is not a picture, and it fails to get the picture stream. Do not perform the following operations
}
width = bufferedImage.getWidth(); // Get through image stream Picture width
height = bufferedImage.getHeight(); // Get image height through image stream
// Omit logical judgment
} catch (Exception e) {
// Omit abnormal operation
}
System.out.println(width);
while (width * scale> maxWidth) {//Process the pixel width of the picture (when the pixel is greater than 1200, the picture is scaled proportionally to the width)
scale -= 0.1;
}
//Mosaic file path
String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
System.out.println(scale);
System.out.println(quality);
System.out.println((int) width * scale);
/*if(true){
return result.toJSONString();
}*/
try {
//Comment out the previous length and width method and use size instead
// Thumbnails.of(filePathName).size(width, height ).toFile(thumbnailFilePathName);
if (size <200 * 1024) {
Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
} else {
Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);/ /(thumbnailFilePathName + "l.");
}
} catch (Exception e1) {
result.put("msg", "The operation failed");
return result.toJSONString();
}
/**
* Thumbnail end
*/
//Original image address
result.put("originalUrl", pathName);
//thumbnail address
result.put("thumbnailUrl", thumbnailPathName);
//thumbnail address
result.put("msg", "The operation was successful");
result.put("status", 200);
return result.toJSONString();
}
}
<dependency>
<groupId >net.coobirdgroupId>
<artifactId >thumbnailatorartifactId>
<version >0.4.8version>
dependency>
String filePathName = "The root path of the image to be compressed";
String thumbnailFilePathName = "Picture path after compression";
double scale = 1d;//image reduction multiple (0~1),1 means keep the original size
double quality = 1d;//The quality of compression, 1 means keep the original size (default 1)
Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);
Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
Thumbnails.of(filePathName).size(400,500).toFile(thumbnailFilePathName);//Change to 400*500, follow the original image scale or zoom to a certain height of 400*
package com.example.atlogging.controller;
import com.alibaba.fastjson.JSONObject;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
@RequestMapping(path = "/thumb", produces = "application/json;charset=UTF-8")
public class TestThumbnails {
/**
* @Description: Save pictures and generate thumbnails
* @param imageFile image file
* @param request request object
* @param uploadPath upload directory
* @return
*/
private static Logger log = LoggerFactory.getLogger(TestThumbnails.class);
@RequestMapping("/up")
public String testThumb(MultipartFile imageFile, HttpServletRequest request) {
String res = this.uploadFileAndCreateThumbnail(imageFile, request, "") ;
return res;
}
public static String uploadFileAndCreateThumbnail(MultipartFile imageFile, HttpServletRequest request, String uploadPath) {
JSONObject result = new JSONObject();
int maxWidth = 1200;//Maximum width of compressed image
if (imageFile == null) {
result.put("msg", "imageFile cannot be empty");
return result.toJSONString();
}
if (imageFile.getSize() >= 10 * 1024 * 1024 ) {
result.put("msg", "The file cannot be larger than 10M");
return result.toJSONString();
}
String uuid = UUID.randomUUID().toString();
String fileDirectory = new SimpleDateFormat("yyyyMMdd").format(new Date());//Set the date format
//Mosaic background file name
String pathName = fileDirectory + File.separator + uuid + "."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//Build and save file path
//Modify the upload path to the server
String realPath = "F:/desktoptemp/ys";//request.getServletContext ().getRealPath("uploadPath");
//Get the server absolute path linux server address Get the current configuration File configuration
//String urlString=PropertiesUtil.getInstance().getSysPro(" uploadPath");
//Mosaic file path
String filePathName = realPath + File.separator + pathName;
log.info("Picture upload path:" + filePathName);
// Determine whether the file save exists
File file = new File(filePathName);
if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
//Create file
file.getParentFile().mkdirs();
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = imageFile.getInputStream();
fileOutputStream = new FileOutputStream(file);
//Write out the file
// IOUtils.copy(inputStream, fileOutputStream);
byte[] buffer = new byte[2048];
IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
buffer = null;
} catch (IOException e) {
filePathName = null;
result.put("msg", "The operation failed");
return result.toJSONString();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
result.put("msg", "The operation failed");
return result.toJSONString();
}
}
//Mosaic background file name
String thumbnailPathName = fileDirectory + File.separator + uuid + "small."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
if (thumbnailPathName.contains(".png")) {
thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
}
long size = imageFile.getSize();
double scale = 1d;
double quality = 1d;
if (size >= 200 * 1024) {//当图片超过200kb的时候进行压缩处理
if (size > 0) {
quality = (200 * 1024f) / size;
}
}
//图片信息
double width = 0;
double height = 0;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile.getInputStream()); //获取图片流
if (bufferedImage == null) {
// 证明上传的文件不是图片,获取图片流失败,不进行下面的操作
}
width = bufferedImage.getWidth(); // 通过图片流获取图片宽度
height = bufferedImage.getHeight(); // 通过图片流获取图片高度
// 省略逻辑判断
} catch (Exception e) {
// 省略异常操作
}
System.out.println(width);
while (width * scale > maxWidth) {//处理图片像素宽度(当像素大于1200时进行图片等比缩放宽度)
scale -= 0.1;
}
//拼接文件路径
String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
System.out.println(scale);
System.out.println(quality);
System.out.println((int) width * scale);
/*if(true){
return result.toJSONString();
}*/
try {
//注释掉之前长宽的方式,改用大小
// Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
if (size < 200 * 1024) {
Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
} else {
Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);//(thumbnailFilePathName + "l.");
}
} catch (Exception e1) {
result.put("msg", "操作失败");
return result.toJSONString();
}
/**
* 缩略图end
*/
//原图地址
result.put("originalUrl", pathName);
//缩略图地址
result.put("thumbnailUrl", thumbnailPathName);
//缩略图地址
result.put("msg", "操作成功");
result.put("status", 200);
return result.toJSONString();
}
}