From 7991ef8cf18ba35736e718bbd9b94c782add9040 Mon Sep 17 00:00:00 2001 From: guqing <38999863+guqing@users.noreply.github.com> Date: Wed, 4 Sep 2024 14:07:43 +0800 Subject: [PATCH] refactor: preserve original image if smaller than requested thumbnail size (#6582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #### What type of PR is this? /kind improvement /area core /milestone 2.20.x #### What this PR does / why we need it: 当生成缩略图时如果原图尺寸小于请求尺寸则返回原图以保持其质量 #### Which issue(s) this PR fixes: Fixes #6579 #### Does this PR introduce a user-facing change? ```release-note 当生成缩略图时如果原图尺寸小于请求尺寸则返回原图以保持其质量 ``` --- .../halo/app/core/attachment/ThumbnailGenerator.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/run/halo/app/core/attachment/ThumbnailGenerator.java b/application/src/main/java/run/halo/app/core/attachment/ThumbnailGenerator.java index 0a6af446f..1bf189d90 100644 --- a/application/src/main/java/run/halo/app/core/attachment/ThumbnailGenerator.java +++ b/application/src/main/java/run/halo/app/core/attachment/ThumbnailGenerator.java @@ -1,5 +1,7 @@ package run.halo.app.core.attachment; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -74,10 +76,14 @@ public class ThumbnailGenerator { throw new UnsupportedOperationException( "Unsupported image format for: " + formatNameOpt.orElse("unknown")); } - var thumbnail = Scalr.resize(img, Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_TO_WIDTH, - size.getWidth()); var formatName = formatNameOpt.orElse("jpg"); var thumbnailFile = getThumbnailFile(formatName); + if (img.getWidth() <= size.getWidth()) { + Files.copy(tempImagePath, thumbnailFile.toPath(), REPLACE_EXISTING); + return; + } + var thumbnail = Scalr.resize(img, Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_TO_WIDTH, + size.getWidth()); ImageIO.write(thumbnail, formatName, thumbnailFile); }