Skip to content

Commit

Permalink
fix: skip thumbnail generation for GIF images (#6597)
Browse files Browse the repository at this point in the history
#### What type of PR is this?
/kind bug
/area core
/milestone 2.20.x

#### What this PR does / why we need it:
修复 GIF 缩略图生成只会保留第一帧的问题

#### Which issue(s) this PR fixes:
Fixes #6596

#### Does this PR introduce a user-facing change?
```release-note
修复 GIF 缩略图生成只会保留第一帧的问题
```
  • Loading branch information
guqing authored Sep 6, 2024
1 parent 6cdd2a7 commit 2ea063d
Showing 1 changed file with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Optional;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.imgscalr.Scalr;
import org.springframework.lang.NonNull;

@Slf4j
@AllArgsConstructor
Expand All @@ -29,6 +31,8 @@ public class ThumbnailGenerator {
*/
static final int MAX_FILE_SIZE = 30 * 1024 * 1024;

private static final Set<String> UNSUPPORTED_FORMATS = Set.of("gif", "svg", "webp");

private final ImageDownloader imageDownloader = new ImageDownloader();
private final ThumbnailSize size;
private final Path storePath;
Expand Down Expand Up @@ -70,13 +74,16 @@ private void generateThumbnail(Path tempImagePath) throws IOException {
if (file.length() > MAX_FILE_SIZE) {
throw new IOException("File size exceeds the limit: " + MAX_FILE_SIZE);
}
var formatNameOpt = getFormatName(file);
String formatName = getFormatName(file)
.orElseThrow(() -> new UnsupportedOperationException("Unknown format"));
if (isUnsupportedFormat(formatName)) {
throw new UnsupportedOperationException("Unsupported image format for: " + formatName);
}

var img = ImageIO.read(file);
if (img == null) {
throw new UnsupportedOperationException(
"Unsupported image format for: " + formatNameOpt.orElse("unknown"));
throw new UnsupportedOperationException("Cannot read image file: " + file);
}
var formatName = formatNameOpt.orElse("jpg");
var thumbnailFile = getThumbnailFile(formatName);
if (img.getWidth() <= size.getWidth()) {
Files.copy(tempImagePath, thumbnailFile.toPath(), REPLACE_EXISTING);
Expand All @@ -87,6 +94,10 @@ private void generateThumbnail(Path tempImagePath) throws IOException {
ImageIO.write(thumbnail, formatName, thumbnailFile);
}

private static boolean isUnsupportedFormat(@NonNull String formatName) {
return UNSUPPORTED_FORMATS.contains(formatName.toLowerCase());
}

private File getThumbnailFile(String formatName) {
return Optional.of(storePath)
.map(path -> {
Expand Down

0 comments on commit 2ea063d

Please sign in to comment.