在线图片转压缩base64、在线图片合并压缩转base64
package com.froad.credit.common.util;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
@Slf4j
public class ImageCompressionUtils {
final static long SIZE_2MB = 2048 * 1024;
final static long SIZE_1MB = 1024 * 1024;
final static long SIZE_512KB = 512 * 1024;
final static long SIZE_256KB = 256 * 1024;
final static long SIZE_128KB = 128 * 1024;
final static long SIZE_64KB = 64 * 1024;
final static long SIZE_32KB = 32 * 1024;
public static String imageToBase64ByOnline(String imagePrefix,String imgURL,String tempPath,String base64Prefix) throws IOException {
long start = System.currentTimeMillis();
ByteArrayOutputStream out = new ByteArrayOutputStream();
String base64;
String filePath = "";
try {
log.info("开始处理imgURL:{}",imagePrefix+imgURL);
BufferedImage read = ImageIO.read(new URL(imagePrefix+imgURL));
log.info("读取图片耗时:{}", System.currentTimeMillis() - start);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String fileString = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";
filePath = tempPath + fileString;
Thumbnails.of(read).scale(1d).toFile(filePath);
File f = new File(filePath);
float scale = 0.0f;
float quality = 0.0f;
long fileSize = f.length();
if (fileSize > SIZE_2MB) {
scale = 0.15f;
quality = 0.3f;
}else if (fileSize > SIZE_1MB) {
scale = 0.2f;
quality = 0.3f;
} else if (fileSize > SIZE_512KB) {
scale = 0.3f;
quality = 0.4f;
} else if (fileSize > SIZE_256KB) {
scale = 0.4f;
quality = 0.5f;
} else if (fileSize > SIZE_128KB) {
scale = 0.5f;
quality = 0.6f;
} else if (fileSize > SIZE_64KB) {
scale = 0.7f;
quality = 0.8f;
} else if (fileSize > SIZE_32KB) {
scale = 0.8f;
quality = 0.9f;
}else {
scale = 0.8f;
quality = 0.9f;
}
Thumbnails.of(filePath).scale(scale).outputQuality(quality).outputFormat("jpg").toOutputStream(out);
base64 = new String(new Base64().encode((out.toByteArray())));
log.info("图片压缩后大小:{}", base64.length());
log.info("图片压缩耗时:{}", System.currentTimeMillis() - start);
}finally {
try{
out.close();
}catch (Exception e){
log.error("关闭流异常:{}", e.getMessage(),e);
}
if(StringUtils.isNotBlank(filePath)){
File file = new File(filePath);
if(file.exists()){
log.info("删除文件结果:{}", file.delete());
}
}
}
return base64Prefix+base64;
}
public static void saveDecodedBase64ImageToLocalFile(String base64ImageString, String filePath) throws IOException {
byte[] imageBytes = new Base64().decode(base64ImageString);
File file = new File(filePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
fileOutputStream.write(imageBytes);
}
}
public static String mergeImageToBase64ByOnline(String imagePrefix,List<String> imagePaths,String tempPath, boolean horizontal, boolean vertical,double scale,double quality,String base64Prefix) throws IOException {
List<String> localImagePaths = new ArrayList<>();
String base64;
long startTime = System.currentTimeMillis();
try{
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
for (String imagePath : imagePaths) {
long downloadTime = System.currentTimeMillis();
String fileString = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";
String filePath = tempPath + fileString;
BufferedImage read = ImageIO.read(new URL(imagePrefix+imagePath));
Thumbnails.of(read).scale(1d).toFile(filePath);
localImagePaths.add(filePath);
log.info("下载图片{}耗时:{}",imagePrefix+imagePath, System.currentTimeMillis() - downloadTime);
}
log.info("下载图片总耗时:{}", System.currentTimeMillis() - startTime);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Thumbnails.of(mergeImages(localImagePaths.toArray(new String[0]), horizontal, vertical)).scale(scale).outputQuality(quality).outputFormat("jpg").toOutputStream(out);
base64 = new String(new Base64().encode((out.toByteArray())));
}finally {
try{
out.close();
}catch (Exception e){
log.error("关闭流异常:{}", e.getMessage(),e);
}
}
}finally {
for (String localImagePath : localImagePaths) {
File file = new File(localImagePath);
if(file.exists()){
log.info("删除文件{}结果:{}", localImagePath,file.delete());
}
}
log.info("图片处理耗时:{}", System.currentTimeMillis() - startTime);
}
return base64Prefix+base64;
}
private static BufferedImage mergeImages(String[] imagePaths, boolean horizontal, boolean vertical) throws IOException {
long start = System.currentTimeMillis();
BufferedImage lastImage = null;
for (String imagePath : imagePaths) {
log.info("开始处理imagePath:{}",imagePath);
if (lastImage == null) {
lastImage = ImageIO.read(new File(imagePath));
} else {
BufferedImage image = ImageIO.read(new File(imagePath));
if (horizontal) {
int width = lastImage.getWidth() + image.getWidth();
int height = Math.max(lastImage.getHeight(), image.getHeight());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(lastImage, 0, 0, null);
graphics.drawImage(image, lastImage.getWidth(), 0, null);
graphics.dispose();
lastImage = bufferedImage;
} else if (vertical) {
int width = Math.max(lastImage.getWidth(), image.getWidth());
int height = lastImage.getHeight() + image.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(lastImage, 0, 0, null);
graphics.drawImage(image, 0, lastImage.getHeight(), null);
graphics.dispose();
lastImage = bufferedImage;
}
}
}
log.info("合并图片耗时:{}", System.currentTimeMillis() - start);
return lastImage;
}
}