Commit 66d4c1e1 by 王欣伟

提交图片压缩

1 parent 11d8d1c7
...@@ -97,6 +97,12 @@ ...@@ -97,6 +97,12 @@
<artifactId>thumbnailator</artifactId> <artifactId>thumbnailator</artifactId>
<version>0.4.8</version> <version>0.4.8</version>
</dependency> </dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-jpeg</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package cn.com.glsx.stdinterface.modules.util;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @Description 文件处理工具
* @author chizw
* @create 2025/4/2 10:45
* @version ver.1.0.0
*/
@Slf4j
@UtilityClass
public class FileComposeUtil {
private static final int MAX_SIZE_BYTES = 500 * 1024;
public static byte[] compressImage(byte[] imageData, float quality) {
if (imageData == null || imageData.length <= MAX_SIZE_BYTES) {
return imageData != null ? imageData : new byte[0];
}
try {
log.info("文件大小 {}B,超过阈值 {}B,开始处理", imageData.length, MAX_SIZE_BYTES);
byte[] compressedData = tryCompress(imageData, quality);
if (compressedData.length <= MAX_SIZE_BYTES) {
return compressedData;
}
return compressedData;
} catch (IOException e) {
log.error("压缩失败: {}", e.getMessage(), e);
return imageData;
}
}
private static byte[] tryCompress(byte[] imageData, float quality) throws IOException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageData)) {
BufferedImage image = readImageWithFallback(bis);
return writeImage(image, quality);
}
}
private static BufferedImage readImageWithFallback(InputStream is) throws IOException {
ImageInputStream iis = ImageIO.createImageInputStream(is);
BufferedImage image = ImageIO.read(iis);
if (image == null) {
throw new IOException("无法读取图片数据");
}
return image;
}
private static byte[] writeImage(BufferedImage image, float quality) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), param);
writer.dispose();
return baos.toByteArray();
}
}
public static void main(String[] args) {
try {
// String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL92AOfCGAAQlTth5qek35.jpeg";
// String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL9qAIBK9AEcWcHoWsf030.jpeg";
byte[] input = Files.readAllBytes(Paths.get("D:\\download\\firefox\\W1K3F5EB3RN326688_20250328132516\\wKgFDWfmL9qAIBK9AEcWcHoWsf030.jpeg"));
float quality = 0.5f;
byte[] output = compressImage(input, quality);
Path write = Files.write(Paths.get("D:\\test\\shield\\output——0002.jpg"), output);
System.out.println("压缩后的文件大小:" + output.length + "字节");
System.out.println(write);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.com.glsx.stdinterface.modules.util;
import javax.imageio.*;
import javax.imageio.plugins.jpeg.JPEGImageReadParam;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
public class NetworkImageCompressor {
static {
// 尝试切换颜色管理系统(需在程序启动时设置)
System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
}
private static BufferedImage downloadImage(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
// 处理重定向
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
String newUrl = conn.getHeaderField("Location");
return downloadImage(newUrl);
}
try (InputStream inputStream = conn.getInputStream()) {
return readImageWithRetry(inputStream);
} finally {
conn.disconnect();
}
}
/**
* 带重试机制的图片读取方法
*/
private static BufferedImage readImageWithRetry(InputStream is) throws IOException {
try {
// 第一次尝试标准读取
return ImageIO.read(is);
} catch (IIOException ex) {
if (ex.getMessage().contains("icc")) {
// ICC配置文件错误时使用备用读取方案
return readImageWithMetadataIgnoring(is);
}
throw ex;
}
}
/**
* 忽略元数据的图片读取方法
*/
private static BufferedImage readImageWithMetadataIgnoring(InputStream is) throws IOException {
ImageInputStream iis = ImageIO.createImageInputStream(is);
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
throw new IOException("No reader for this image format");
}
ImageReader reader = readers.next();
reader.setInput(iis);
// 配置读取参数
JPEGImageReadParam param = new JPEGImageReadParam();
param.setSourceRegion(null); // 读取整个图片
param.setSourceSubsampling(1, 1, 0, 0); // 不进行子采样
// 禁用元数据处理
ImageReadParam readParam = reader.getDefaultReadParam();
readParam.setSourceSubsampling(1, 1, 0, 0);
try {
return reader.read(0, readParam);
} finally {
reader.dispose();
iis.close();
}
}
/**
* 从URL获取图片并压缩到指定大小
* @param imageUrl 图片网络地址
* @param maxSizeKB 最大文件大小(单位KB)
* @return 压缩后的图片字节数据
*/
public static byte[] compressFromUrl(String imageUrl, int maxSizeKB) throws IOException {
final long maxBytes = maxSizeKB * 1024L;
// 从URL获取图片
BufferedImage image = downloadImage(imageUrl);
// 获取JPEG编码器
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
// 创建压缩参数
JPEGImageWriteParam param = new JPEGImageWriteParam(null);
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
float quality = 0.9f;
int attempt = 0;
do {
baos.reset(); // 重置输出流
param.setCompressionQuality(quality);
try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(baos)) {
writer.setOutput(output);
writer.write(null, new IIOImage(image, null, null), param);
}
// 检查大小
if (baos.size() <= maxBytes) {
break;
}
// 动态调整质量
float oversizeRatio = (float) baos.size() / maxBytes;
quality *= Math.max(0.5f, 1 / oversizeRatio);
} while (quality > 0.1f && attempt++ < 20);
writer.dispose();
// 最终验证
if (baos.size() > maxBytes) {
throw new IOException("压缩失败:无法在保持质量的情况下达到目标大小");
}
return baos.toByteArray();
}
// 使用示例
public static void main(String[] args) {
try {
// String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL92AOfCGAAQlTth5qek35.jpeg";
String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL9qAIBK9AEcWcHoWsf030.jpeg";
byte[] compressedData = compressFromUrl(url, 1024);
System.out.println("压缩后大小:" + compressedData.length / 1024 + "KB");
String filePath = "D:\\test\\shield\\";
// 将bytes输出到文件
try (FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7003.jpg")) {
fos.write(compressedData);
fos.flush();
fos.close();
System.out.println("文件已保存到:" + filePath);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
\ No newline at end of file \ No newline at end of file
...@@ -4,11 +4,12 @@ import cn.hutool.core.date.StopWatch; ...@@ -4,11 +4,12 @@ import cn.hutool.core.date.StopWatch;
import com.glsx.plat.common.utils.HttpUtils; import com.glsx.plat.common.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import java.io.*; import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Arrays;
/** /**
* @author Administrator * @author Administrator
...@@ -70,14 +71,16 @@ public class ThumbnailatorUtil { ...@@ -70,14 +71,16 @@ public class ThumbnailatorUtil {
* @param imageUrl * @param imageUrl
*/ */
public static byte[] compressImage(String imageUrl) { public static byte[] compressImage(String imageUrl) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
double outputQuality = 1.0d; double outputQuality = 1.0d;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
URL url = new URL(imageUrl); URL url = new URL(imageUrl);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
conn.setRequestProperty("Range", "bytes=0-"); conn.setRequestProperty("Range", "bytes=0-");
long fileSize = conn.getContentLength(); long fileSize = conn.getContentLength();
log.info("fileSize===" + fileSize); log.info("fileSize===" + fileSize);
if (fileSize > 1.2 * 1024 * 1024) { boolean comp = true;
// if (fileSize > 1.2 * 1024 * 1024) {
if (comp) {
if (fileSize >= 10 * 1024 * 1024) { if (fileSize >= 10 * 1024 * 1024) {
outputQuality = 0.1d; outputQuality = 0.1d;
} else if (8 * 1024 * 1024 <= fileSize && fileSize < 10 * 1024 * 1024) { } else if (8 * 1024 * 1024 <= fileSize && fileSize < 10 * 1024 * 1024) {
...@@ -97,20 +100,57 @@ public class ThumbnailatorUtil { ...@@ -97,20 +100,57 @@ public class ThumbnailatorUtil {
} else if (1.2 * 1024 * 1024 <= fileSize && fileSize < 2 * 1024 * 1024) { } else if (1.2 * 1024 * 1024 <= fileSize && fileSize < 2 * 1024 * 1024) {
outputQuality = 0.75d; outputQuality = 0.75d;
} }
log.debug("======outputQuality:" + outputQuality);
Thumbnails.of(url) Thumbnails.of(url)
.scale(1.0d) .scale(1.0d)
.outputQuality(outputQuality) .outputQuality(outputQuality)
.toOutputStream(baos); .toOutputStream(baos);
return baos.toByteArray(); return baos.toByteArray();
} else { } else {
log.debug("======down======");
return HttpUtils.downloadBytes(imageUrl); return HttpUtils.downloadBytes(imageUrl);
} }
} catch (Exception e) { } catch (Exception e) {
log.error("图片压缩异常" + e.getMessage(), e); log.error("图片压缩异常" + e.getMessage(), e);
try {
// outputQuality转为float格式
float floatQuality = (float) outputQuality;
byte[] imageBytes = downloadImage(imageUrl);
return FileComposeUtil.compressImage(imageBytes, floatQuality);
} catch (IOException ex) {
ex.printStackTrace();
}
} }
return null; return null;
} }
private static byte[] downloadImage(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
// 处理重定向
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
String newUrl = conn.getHeaderField("Location");
return downloadImage(newUrl);
}
try (InputStream inputStream = conn.getInputStream()) {
// 读取图片为byte[]
byte[] imageBytes = IOUtils.toByteArray(inputStream);
return imageBytes;
} finally {
conn.disconnect();
}
}
/** /**
* 将图片压缩到1.2M以下 * 将图片压缩到1.2M以下
* *
...@@ -126,18 +166,27 @@ public class ThumbnailatorUtil { ...@@ -126,18 +166,27 @@ public class ThumbnailatorUtil {
} }
public static void main(String[] args) throws FileNotFoundException { public static void main(String[] args) throws FileNotFoundException {
String filePath = "D:\\"; String filePath = "D:\\test\\shield\\";
// String filename = "wKgFHWNbGFCAJ3gZAOZukG_6uyQ678.jpg"; // String filename = "wKgFHWNbGFCAJ3gZAOZukG_6uyQ678.jpg";
// String destFilename = "compressed_" + filename; // String destFilename = "compressed_" + filename;
// ThumbnailatorUtil.compressImage(filePath, filename, destFilename); // ThumbnailatorUtil.compressImage(filePath, filename, destFilename);
String url = "https://wx.glsx.com.cn/upload/biz/5a9a9ef0-646e-4c9e-8d9e-d07c373d56b7.jpg"; // String url = "https://wx.glsx.com.cn/upload/biz/5a9a9ef0-646e-4c9e-8d9e-d07c373d56b7.jpg";
FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7.jpg"); // String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL92AOfCGAAQlTth5qek35.jpeg";
compressImage(url); String url = "https://bhg.didihu.com.cn/group1/M00/48/DC/wKgFDWfmL9qAIBK9AEcWcHoWsf030.jpeg";
// FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7.jpg");
byte[] bytes = compressImage(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); /*ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressImage(url); compressImage(url);
byte[] compressImageBytes = baos.toByteArray(); byte[] compressImageBytes = baos.toByteArray();
System.out.println("compressImageBytes = " + Arrays.toString(compressImageBytes)); System.out.println("compressImageBytes = " + Arrays.toString(compressImageBytes));*/
// 将bytes输出到文件
try (FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7004.jpg")) {
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!