优化水印
This commit is contained in:
@@ -11,8 +11,6 @@ import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -22,17 +20,10 @@ public class ImageWatermarkUtil {
|
||||
private final WatermarkProperties watermarkProperties;
|
||||
private final MinioUtil minioUtil;
|
||||
|
||||
private static final String WATERMARK_CACHE_PREFIX = "watermark:";
|
||||
private static final int PRESIGNED_URL_EXPIRE_SECONDS = 7 * 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* 全局水印结果缓存,key = 原图 logical path hash,value = 带水印图片的 logical path
|
||||
*/
|
||||
private final Map<String, String> watermarkCache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 对指定 MinIO 资源添加平铺文字水印,返回带水印图片的 presigned URL。
|
||||
* 相同原图结果会被缓存 30 天。
|
||||
* 对指定 MinIO 资源添加平铺文字水印,返回带水印图片的 presigned URL(有效期 7 天)。
|
||||
*/
|
||||
public String applyWatermark(String minioResource) {
|
||||
try {
|
||||
@@ -40,13 +31,6 @@ public class ImageWatermarkUtil {
|
||||
? minioUtil.getLogicalPathFromPresignedUrl(minioResource)
|
||||
: minioResource.trim();
|
||||
|
||||
String cacheKey = String.valueOf(logicalPath.hashCode());
|
||||
|
||||
String cachedPath = watermarkCache.get(cacheKey);
|
||||
if (cachedPath != null) {
|
||||
return minioUtil.getImageUrl(cachedPath, PRESIGNED_URL_EXPIRE_SECONDS);
|
||||
}
|
||||
|
||||
try (InputStream originalStream = minioUtil.downloadFile(logicalPath);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
|
||||
@@ -55,8 +39,6 @@ public class ImageWatermarkUtil {
|
||||
detectContentType(logicalPath));
|
||||
|
||||
String newPath = uploadWatermarkedImage(watermarkedBytes, logicalPath);
|
||||
watermarkCache.put(cacheKey, newPath);
|
||||
|
||||
return minioUtil.getImageUrl(newPath, PRESIGNED_URL_EXPIRE_SECONDS);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -141,18 +123,4 @@ public class ImageWatermarkUtil {
|
||||
if (lower.endsWith(".webp")) return "image/webp";
|
||||
return "image/jpeg";
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定原图的水印缓存(供外部在原图更新时调用)
|
||||
*/
|
||||
public void evictCache(String minioResource) {
|
||||
try {
|
||||
String logicalPath = minioUtil.isPresignedUrl(minioResource)
|
||||
? minioUtil.getLogicalPathFromPresignedUrl(minioResource)
|
||||
: minioResource.trim();
|
||||
watermarkCache.remove(String.valueOf(logicalPath.hashCode()));
|
||||
} catch (Exception e) {
|
||||
log.warn("清理水印缓存失败 resource={}", minioResource, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user