refactor(images): migrate to TwelveMonkeys ImageIO with graceful unsupported format handling (#2188)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Co-authored-by: ACX <8075870+acx10@users.noreply.github.com>
This commit is contained in:
Balázs Szücs
2026-01-07 18:12:12 -07:00
committed by GitHub
co-authored by ACX
parent c17fe58f4c
commit f0444df6ee
10 changed files with 134 additions and 60 deletions
@@ -28,6 +28,7 @@ public class KoboBookMetadata {
private String language = "en";
private String isbn;
@Builder.Default
private String genre = "00000000-0000-0000-0000-000000000001";
private String slug;
private String coverImageId;
@@ -9,12 +9,15 @@ import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Objects;
import static net.lingala.zip4j.util.FileUtils.getFileExtension;
@Slf4j
@Service
@RequiredArgsConstructor
@@ -34,20 +37,26 @@ public class BackgroundUploadService {
String extension = getFileExtension(originalFilename);
String filename = "1." + extension;
try (InputStream inputStream = file.getInputStream()) {
BufferedImage originalImage;
try (InputStream inputStream = file.getInputStream()) {
originalImage = ImageIO.read(inputStream);
try {
originalImage = FileService.readImage(inputStream);
} catch (IOException e) {
originalImage = null;
}
if (originalImage == null) {
throw new IllegalArgumentException("Invalid image file");
}
deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId);
originalImage.flush(); // Release resources after saving
String fileUrl = FileService.getBackgroundUrl(filename, userId);
return new UploadResponse(fileUrl);
}
} catch (Exception e) {
log.error("Failed to upload background file: {}", e.getMessage(), e);
throw new RuntimeException("Failed to upload file: " + e.getMessage(), e);
@@ -62,6 +71,9 @@ public class BackgroundUploadService {
String filename = "1." + extension;
BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl);
if (originalImage == null) {
throw new IllegalArgumentException("Failed to download or decode image from URL");
}
deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId);
@@ -146,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
.min(Comparator.comparing(ZipArchiveEntry::getName))
.map(entry -> {
try (InputStream is = zipFile.getInputStream(entry)) {
return ImageIO.read(is);
return FileService.readImage(is);
} catch (Exception e) {
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
return null;
@@ -177,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
if (bytesRead < 0) break;
offset += bytesRead;
}
return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content)));
return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(content)));
}
}
}
@@ -198,7 +198,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
for (FileHeader header : imageHeaders) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
archive.extractFile(header, baos);
return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray())));
return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(baos.toByteArray())));
} catch (Exception e) {
log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage());
}
@@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
boolean saved;
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = ImageIO.read(bais);
BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) {
log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName());
log.warn("Failed to decode cover image for EPUB '{}'", bookEntity.getFileName());
return false;
}
saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
@@ -125,13 +125,12 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce
}
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData));
try {
return fileService.saveCoverImages(originalImage, bookId);
} finally {
if (originalImage != null) {
originalImage.flush(); // Release resources after processing
}
BufferedImage originalImage = FileService.readImage(coverData);
if (originalImage == null) {
log.warn("Failed to decode cover image for FB2");
return false;
}
return fileService.saveCoverImages(originalImage, bookId);
}
}
@@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import com.adityachandel.booklore.util.FileService;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
@@ -314,7 +316,8 @@ public class CbxConversionService {
return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
lowerName.endsWith(".png") || lowerName.endsWith(".webp") ||
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp");
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") ||
lowerName.endsWith(".avif") || lowerName.endsWith(".heic");
}
private boolean isJpegFile(Path path) {
@@ -404,7 +407,13 @@ public class CbxConversionService {
}
} else {
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
BufferedImage image = ImageIO.read(fis);
BufferedImage image = null;
try {
image = FileService.readImage(fis);
} catch (Exception e) {
log.debug("Failed to decode image {} with FileService: {}", sourceImagePath, e.getMessage());
}
if (image != null) {
writeJpegImage(image, zipOut, compressionPercentage/100f);
} else {
@@ -40,7 +40,7 @@ public class CbxReaderService {
private static final String CBZ_EXTENSION = ".cbz";
private static final String CBR_EXTENSION = ".cbr";
private static final String CB7_EXTENSION = ".cb7";
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"};
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"};
private final BookRepository bookRepository;
private final AppSettingService appSettingService;
@@ -144,6 +144,28 @@ public class FileService {
// IMAGE OPERATIONS
// ========================================
public static BufferedImage readImage(InputStream inputStream) throws IOException {
return readImage(inputStream.readAllBytes());
}
public static BufferedImage readImage(byte[] imageData) throws IOException {
if (imageData == null || imageData.length == 0) {
throw new IOException("Image data is null or empty");
}
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage image = ImageIO.read(is);
if (image != null) {
return image;
}
} catch (Exception e) {
log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage());
return null;
}
log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)");
return null;
}
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
@@ -156,9 +178,10 @@ public class FileService {
public static void saveImage(byte[] imageData, String filePath) throws IOException {
BufferedImage originalImage = null;
try {
originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
originalImage = readImage(imageData);
if (originalImage == null) {
throw new IOException("Invalid image data: unable to decode image");
log.warn("Skipping saveImage for {}: decoded image is null", filePath);
return;
}
File outputFile = new File(filePath);
File parentDir = outputFile.getParentFile();
@@ -191,13 +214,7 @@ public class FileService {
// Validate and convert
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) {
BufferedImage image = ImageIO.read(inputStream);
if (image == null) {
throw new IOException("Downloaded content is not a supported image format.");
}
return image;
}
return readImage(response.getBody());
} else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
}
@@ -216,10 +233,11 @@ public class FileService {
validateCoverFile(file);
BufferedImage originalImage;
try (InputStream inputStream = file.getInputStream()) {
originalImage = ImageIO.read(inputStream);
originalImage = readImage(inputStream);
}
if (originalImage == null) {
throw ApiError.IMAGE_NOT_FOUND.createException();
log.warn("Could not decode image from file, skipping thumbnail creation for book: {}", bookId);
return;
}
boolean success = saveCoverImages(originalImage, bookId);
if (!success) {
@@ -235,12 +253,10 @@ public class FileService {
public void createThumbnailFromBytes(long bookId, byte[] imageBytes) {
try {
BufferedImage originalImage;
try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) {
originalImage = ImageIO.read(inputStream);
}
BufferedImage originalImage = readImage(imageBytes);
if (originalImage == null) {
throw ApiError.IMAGE_NOT_FOUND.createException();
log.warn("Skipping thumbnail creation for book {}: image decode failed", bookId);
return;
}
boolean success = saveCoverImages(originalImage, bookId);
if (!success) {
@@ -257,6 +273,10 @@ public class FileService {
public void createThumbnailFromUrl(long bookId, String imageUrl) {
try {
BufferedImage originalImage = downloadImageFromUrl(imageUrl);
if (originalImage == null) {
log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId);
return;
}
boolean success = saveCoverImages(originalImage, bookId);
if (!success) {
throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images");