Commit ada05e2c by 王欣伟

Merge branch 'develop'

2 parents 5da9d579 247b5382
......@@ -97,6 +97,12 @@
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-jpeg</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<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
......@@ -4,11 +4,12 @@ import cn.hutool.core.date.StopWatch;
import com.glsx.plat.common.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
/**
* @author Administrator
......@@ -70,14 +71,16 @@ public class ThumbnailatorUtil {
* @param imageUrl
*/
public static byte[] compressImage(String imageUrl) {
double outputQuality = 1.0d;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
double outputQuality = 1.0d;
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.setRequestProperty("Range", "bytes=0-");
long fileSize = conn.getContentLength();
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) {
outputQuality = 0.1d;
} else if (8 * 1024 * 1024 <= fileSize && fileSize < 10 * 1024 * 1024) {
......@@ -97,20 +100,57 @@ public class ThumbnailatorUtil {
} else if (1.2 * 1024 * 1024 <= fileSize && fileSize < 2 * 1024 * 1024) {
outputQuality = 0.75d;
}
log.debug("======outputQuality:" + outputQuality);
Thumbnails.of(url)
.scale(1.0d)
.outputQuality(outputQuality)
.toOutputStream(baos);
return baos.toByteArray();
} else {
log.debug("======down======");
return HttpUtils.downloadBytes(imageUrl);
}
} catch (Exception 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;
}
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以下
*
......@@ -126,18 +166,27 @@ public class ThumbnailatorUtil {
}
public static void main(String[] args) throws FileNotFoundException {
String filePath = "D:\\";
String filePath = "D:\\test\\shield\\";
// String filename = "wKgFHWNbGFCAJ3gZAOZukG_6uyQ678.jpg";
// String destFilename = "compressed_" + filename;
// ThumbnailatorUtil.compressImage(filePath, filename, destFilename);
String url = "https://wx.glsx.com.cn/upload/biz/5a9a9ef0-646e-4c9e-8d9e-d07c373d56b7.jpg";
FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7.jpg");
compressImage(url);
// String url = "https://wx.glsx.com.cn/upload/biz/5a9a9ef0-646e-4c9e-8d9e-d07c373d56b7.jpg";
// 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";
// FileOutputStream fos = new FileOutputStream(filePath + "compressed_" + "d07c373d56b7.jpg");
byte[] bytes = compressImage(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressImage(url);
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();
}
}
}
package cn.com.glsx.stdinterface.modules.service;
import cn.hutool.json.JSONUtil;
import com.glsx.plat.common.utils.HttpUtils;
import java.util.TreeMap;
/**
* @BelongsProject: ne-shield-standard-interfaces
* @BelongsPackage: cn.com.glsx.stdinterface.modules.service
* @Author: dell_xw
* @CreateTime: 2023-09-04 16:43
* @Description: TODO
* @Version: 1.0
*/
public class BhgWorkOrderSyncTest {
public static void main(String[] args) {
String bhgOrderServiceUrl = "http://bhg.didihu.com.cn/carservice/ordercenter/";
String url = bhgOrderServiceUrl + "api/standardOrder/save?";
TreeMap<String, Object> map = new TreeMap<>();
map.put("address", "苏州大道东456号");
map.put("carColor", "");
map.put("carOwner", "辰宇宁精密机械(昆山)有限公司");
map.put("carOwnerPhone", "");
map.put("carType", "小型轿车");
map.put("channel", "glsx_nes");
map.put("contact", "");
map.put("district", "");
map.put("expectInstallTime", "2023-09-05");
map.put("installContactNumber", "");
map.put("installContacts", "");
map.put("merchantName", "仲利国际电销组");
map.put("phoneNumber", "13160028059");
map.put("remark", "租赁公司-仲利国际租赁有限公司 申请编号—AP2023083184489 区域—无 设备组合—GPSC:700B:1;GPSW:703B:1 导入时间—2023-09-04 分公司—无 店面名称—仲利国际电销组 店面联系电话—13160028059 要求安装日期—2023-09-05 客户姓名—辰宇宁精密机械(昆山)有限公司 车架号—LVSHFFAL4JF726278 颜色—无 车型—小型轿车 贷款期限—无 租凭方式—无 安装地址—苏州大道东456号 备注—无 安装方式—广联安装");
map.put("serviceCode", "NES_ZLGJ011");
map.put("sign", "EE455CA6E1BE91D6F88AC9D412771BC2");
map.put("vinNo", "LVSHFFAL4JF726278");
map.put("workOrderNo", "AP2023083184489");
String body = JSONUtil.toJsonStr(map);
String result = HttpUtils.post(url, body);
System.out.println("同步工单 到包活干结果:{}" + result);
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!