feat(printer): 实现照片自动裁剪功能

- 添加打印尺寸获取逻辑,优先从打印机配置读取
- 实现默认尺寸 fallback 机制 (1020x1520)
- 集成 smartCropAndFill 图片裁剪算法
- 添加裁剪后图片上传和临时文件清理
- 增加异常处理,裁剪失败时回退到原图
-优化图片 URL 内部访问地址配置
This commit is contained in:
2025-11-06 15:32:11 +08:00
parent dcc8cdeb6a
commit fb3a08fdcf
2 changed files with 56 additions and 3 deletions

View File

@@ -369,12 +369,65 @@ public class PrinterServiceImpl implements PrinterService {
resultIds.add(null);
return;
}
String url = byId.getUrl();
MemberPrintEntity entity = new MemberPrintEntity();
entity.setMemberId(memberId);
entity.setScenicId(scenicId);
entity.setFaceId(faceId);
entity.setOrigUrl(byId.getUrl());
entity.setCropUrl(byId.getUrl());
entity.setOrigUrl(url);
// 获取打印尺寸并裁剪图片
String cropUrl = url; // 默认使用原图
try {
// 从打印机表获取尺寸
Integer printWidth = null;
Integer printHeight = null;
List<PrinterResp> printers = printerMapper.listByScenicId(scenicId);
if (printers != null && !printers.isEmpty()) {
PrinterResp firstPrinter = printers.get(0);
printWidth = firstPrinter.getPreferW();
printHeight = firstPrinter.getPreferH();
log.debug("从打印机获取尺寸: scenicId={}, printerId={}, width={}, height={}",
scenicId, firstPrinter.getId(), printWidth, printHeight);
}
// 如果打印机没有配置或配置无效,使用默认值
if (printWidth == null || printWidth <= 0) {
printWidth = 1020;
log.debug("打印机宽度未配置或无效,使用默认值: width={}", printWidth);
}
if (printHeight == null || printHeight <= 0) {
printHeight = 1520;
log.debug("打印机高度未配置或无效,使用默认值: height={}", printHeight);
}
// 使用smartCropAndFill裁剪图片
File croppedFile = ImageUtils.smartCropAndFill(url, printWidth, printHeight);
try {
// 上传裁剪后的图片
String[] split = url.split("\\.");
String ext = split.length > 0 ? split[split.length - 1] : "jpg";
cropUrl = StorageFactory.use().uploadFile(null, croppedFile, "printer", UUID.randomUUID() + "." + ext);
log.info("照片裁剪成功: memberId={}, scenicId={}, sourceId={}, 原图={}, 裁剪后={}, 尺寸={}x{}",
memberId, scenicId, id, url, cropUrl, printWidth, printHeight);
} finally {
// 清理临时文件
if (croppedFile != null && croppedFile.exists()) {
croppedFile.delete();
}
}
} catch (Exception e) {
log.error("照片裁剪失败,使用原图: memberId={}, scenicId={}, sourceId={}, url={}", memberId, scenicId, id, url, e);
// 出现异常则使用原图
cropUrl = url;
}
entity.setCropUrl(cropUrl);
entity.setStatus(0);
try {

View File

@@ -263,7 +263,7 @@ public class ImageUtils {
String urlStr = (String) imageSource;
if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
// 从URL加载
java.net.URL url = new java.net.URL(urlStr);
java.net.URL url = new java.net.URL(urlStr.replace("oss.zhentuai.com", "frametour-assets.oss-cn-shanghai-internal.aliyuncs.com"));
return ImageIO.read(url);
} else {
// 作为文件路径处理