feat:
1. add ImageBase64Compressor
This commit is contained in:
@@ -0,0 +1,148 @@
|
|||||||
|
package com.fly.boot.biz.ar.util;
|
||||||
|
|
||||||
|
import javax.imageio.IIOImage;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.ImageWriteParam;
|
||||||
|
import javax.imageio.ImageWriter;
|
||||||
|
import javax.imageio.stream.ImageOutputStream;
|
||||||
|
import java.awt.*;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.*;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Iterator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片压缩工具类:将用户上传的图片压缩并转为 Base64,确保 Base64 字符串 ≤ 2MB
|
||||||
|
*/
|
||||||
|
public class ImageBase64Compressor {
|
||||||
|
|
||||||
|
// 最大 Base64 字符串大小:2MB = 2 * 1024 * 1024 字节
|
||||||
|
public static final int MAX_BASE64_SIZE_BYTES = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 压缩用户上传的图片,并返回 Base64 字符串(带 data URL 前缀),确保 ≤ 2MB
|
||||||
|
*
|
||||||
|
* @param imageBytes 用户上传的原始图片字节数组(如来自 MultipartFile.getBytes())
|
||||||
|
* @return 格式为 "data:image/jpeg;base64,xxxx" 的字符串,长度 ≤ 2MB
|
||||||
|
* @throws IllegalArgumentException 图片无效或无法压缩到目标大小
|
||||||
|
* @throws IOException IO 异常
|
||||||
|
*/
|
||||||
|
public static String compressToBase64Under2MB(byte[] imageBytes) throws IOException {
|
||||||
|
if (imageBytes == null || imageBytes.length == 0) {
|
||||||
|
throw new IllegalArgumentException("上传的图片为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: 读取原始图片
|
||||||
|
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
|
||||||
|
if (originalImage == null) {
|
||||||
|
throw new IllegalArgumentException("不支持的图片格式,请上传 JPG/PNG 等常见格式");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: 转为 RGB 格式(确保兼容 JPEG)
|
||||||
|
BufferedImage rgbImage = toRGBBufferedImage(originalImage);
|
||||||
|
|
||||||
|
// Step 3: 如果分辨率过高,先缩放到合理尺寸(如 ≤ 1920px)
|
||||||
|
if (rgbImage.getWidth() > 1920 || rgbImage.getHeight() > 1920) {
|
||||||
|
rgbImage = scaleImagePreserveRatio(rgbImage, 1920);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 4: 通过质量压缩 + 迭代逼近,确保 Base64 ≤ 2MB
|
||||||
|
byte[] compressedBytes = compressWithTargetBase64Size(rgbImage, MAX_BASE64_SIZE_BYTES);
|
||||||
|
|
||||||
|
// Step 5: 转为 Base64 字符串
|
||||||
|
String base64Data = Base64.getEncoder().encodeToString(compressedBytes);
|
||||||
|
String result = "data:image/jpeg;base64," + base64Data;
|
||||||
|
|
||||||
|
// 最终校验(防御性编程)
|
||||||
|
if (result.getBytes().length > MAX_BASE64_SIZE_BYTES) {
|
||||||
|
throw new IllegalArgumentException("图片过于复杂,无法压缩至 2MB 以内");
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------ 工具方法 ------------------
|
||||||
|
|
||||||
|
private static BufferedImage toRGBBufferedImage(BufferedImage src) {
|
||||||
|
if (src.getType() == BufferedImage.TYPE_INT_RGB) {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
BufferedImage rgb = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
|
||||||
|
Graphics2D g = rgb.createGraphics();
|
||||||
|
g.drawImage(src, 0, 0, null);
|
||||||
|
g.dispose();
|
||||||
|
return rgb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按比例缩放图像,使长边不超过 maxDimension
|
||||||
|
*/
|
||||||
|
private static BufferedImage scaleImagePreserveRatio(BufferedImage img, int maxDimension) {
|
||||||
|
int width = img.getWidth();
|
||||||
|
int height = img.getHeight();
|
||||||
|
if (width <= maxDimension && height <= maxDimension) {
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
double ratio = Math.min((double) maxDimension / width, (double) maxDimension / height);
|
||||||
|
int newWidth = (int) (width * ratio);
|
||||||
|
int newHeight = (int) (height * ratio);
|
||||||
|
|
||||||
|
Image scaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
|
||||||
|
BufferedImage scaledBI = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
|
||||||
|
Graphics2D g = scaledBI.createGraphics();
|
||||||
|
g.drawImage(scaled, 0, 0, null);
|
||||||
|
g.dispose();
|
||||||
|
return scaledBI;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 压缩图像,使其 Base64 编码后 ≤ maxBase64SizeBytes
|
||||||
|
*/
|
||||||
|
private static byte[] compressWithTargetBase64Size(BufferedImage image, int maxBase64SizeBytes) throws IOException {
|
||||||
|
// Base64 长度 = ceil(n/3)*4,反推最大允许的二进制大小
|
||||||
|
int maxBinarySize = (int) Math.floor(maxBase64SizeBytes * 0.75); // 保守估计
|
||||||
|
|
||||||
|
float quality = 0.95f; // 初始高质量
|
||||||
|
byte[] compressedBytes;
|
||||||
|
do {
|
||||||
|
compressedBytes = compressJpeg(image, quality);
|
||||||
|
if (getBase64ByteLength(compressedBytes) <= maxBase64SizeBytes) {
|
||||||
|
return compressedBytes;
|
||||||
|
}
|
||||||
|
quality -= 0.05; // 每次循环减少质量
|
||||||
|
} while (quality > 0.05); // 确保质量不低于0.05
|
||||||
|
|
||||||
|
// 如果即使在最低质量下仍然超过2MB,则返回最后一次尝试的结果。
|
||||||
|
return compressedBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算 Base64 编码后的字节长度(不实际编码,避免性能开销)
|
||||||
|
*/
|
||||||
|
private static int getBase64ByteLength(byte[] binaryData) {
|
||||||
|
return ((binaryData.length + 2) / 3) * 4; // 等价于 Base64.getEncoder().encode(binaryData).length
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用指定质量压缩为 JPEG
|
||||||
|
*/
|
||||||
|
private static byte[] compressJpeg(BufferedImage image, float quality) throws IOException {
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
|
||||||
|
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
|
||||||
|
if (!writers.hasNext()) {
|
||||||
|
throw new IllegalStateException("系统不支持 JPEG 写入");
|
||||||
|
}
|
||||||
|
ImageWriter writer = writers.next();
|
||||||
|
writer.setOutput(ios);
|
||||||
|
|
||||||
|
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||||
|
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||||
|
param.setCompressionQuality(Math.max(0.01f, Math.min(1.0f, quality)));
|
||||||
|
|
||||||
|
writer.write(null, new IIOImage(image, null, null), param);
|
||||||
|
writer.dispose();
|
||||||
|
}
|
||||||
|
return baos.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user