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
+7 -2
View File
@@ -58,8 +58,13 @@ dependencies {
implementation 'org.apache.pdfbox:pdfbox-io:3.0.6' implementation 'org.apache.pdfbox:pdfbox-io:3.0.6'
implementation 'org.apache.pdfbox:xmpbox:3.0.6' implementation 'org.apache.pdfbox:xmpbox:3.0.6'
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4' implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0' // --- TwelveMonkeys ImageIO ---
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0'
implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0'
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0'
implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0'
implementation 'io.documentnode:epub4j-core:4.2.2' implementation 'io.documentnode:epub4j-core:4.2.2'
// --- UNRAR Support --- // --- UNRAR Support ---
@@ -28,6 +28,7 @@ public class KoboBookMetadata {
private String language = "en"; private String language = "en";
private String isbn; private String isbn;
@Builder.Default
private String genre = "00000000-0000-0000-0000-000000000001"; private String genre = "00000000-0000-0000-0000-000000000001";
private String slug; private String slug;
private String coverImageId; private String coverImageId;
@@ -9,12 +9,15 @@ import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Objects; import java.util.Objects;
import static net.lingala.zip4j.util.FileUtils.getFileExtension;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -34,20 +37,26 @@ public class BackgroundUploadService {
String extension = getFileExtension(originalFilename); String extension = getFileExtension(originalFilename);
String filename = "1." + extension; String filename = "1." + extension;
try (InputStream inputStream = file.getInputStream()) {
BufferedImage originalImage; BufferedImage originalImage;
try (InputStream inputStream = file.getInputStream()) { try {
originalImage = ImageIO.read(inputStream); originalImage = FileService.readImage(inputStream);
} catch (IOException e) {
originalImage = null;
} }
if (originalImage == null) { if (originalImage == null) {
throw new IllegalArgumentException("Invalid image file"); throw new IllegalArgumentException("Invalid image file");
} }
deleteExistingBackgroundFiles(userId); deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId); fileService.saveBackgroundImage(originalImage, filename, userId);
originalImage.flush(); // Release resources after saving originalImage.flush(); // Release resources after saving
String fileUrl = FileService.getBackgroundUrl(filename, userId); String fileUrl = FileService.getBackgroundUrl(filename, userId);
return new UploadResponse(fileUrl); return new UploadResponse(fileUrl);
}
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to upload background file: {}", e.getMessage(), e); log.error("Failed to upload background file: {}", e.getMessage(), e);
throw new RuntimeException("Failed to upload 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; String filename = "1." + extension;
BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl);
if (originalImage == null) {
throw new IllegalArgumentException("Failed to download or decode image from URL");
}
deleteExistingBackgroundFiles(userId); deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId); fileService.saveBackgroundImage(originalImage, filename, userId);
@@ -146,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
.min(Comparator.comparing(ZipArchiveEntry::getName)) .min(Comparator.comparing(ZipArchiveEntry::getName))
.map(entry -> { .map(entry -> {
try (InputStream is = zipFile.getInputStream(entry)) { try (InputStream is = zipFile.getInputStream(entry)) {
return ImageIO.read(is); return FileService.readImage(is);
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage()); log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
return null; return null;
@@ -177,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
if (bytesRead < 0) break; if (bytesRead < 0) break;
offset += bytesRead; 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) { for (FileHeader header : imageHeaders) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
archive.extractFile(header, baos); 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) { } catch (Exception e) {
log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage()); log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage());
} }
@@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
boolean saved; boolean saved;
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = ImageIO.read(bais); BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) { 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; return false;
} }
saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); 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 { private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData)); BufferedImage originalImage = FileService.readImage(coverData);
try { if (originalImage == null) {
return fileService.saveCoverImages(originalImage, bookId); log.warn("Failed to decode cover image for FB2");
} finally { return false;
if (originalImage != null) {
originalImage.flush(); // Release resources after processing
}
} }
return fileService.saveCoverImages(originalImage, bookId);
} }
} }
@@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import com.adityachandel.booklore.util.FileService;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter; import javax.imageio.ImageWriter;
@@ -314,7 +316,8 @@ public class CbxConversionService {
return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
lowerName.endsWith(".png") || lowerName.endsWith(".webp") || 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) { private boolean isJpegFile(Path path) {
@@ -404,7 +407,13 @@ public class CbxConversionService {
} }
} else { } else {
try (InputStream fis = Files.newInputStream(sourceImagePath)) { 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) { if (image != null) {
writeJpegImage(image, zipOut, compressionPercentage/100f); writeJpegImage(image, zipOut, compressionPercentage/100f);
} else { } else {
@@ -40,7 +40,7 @@ public class CbxReaderService {
private static final String CBZ_EXTENSION = ".cbz"; private static final String CBZ_EXTENSION = ".cbz";
private static final String CBR_EXTENSION = ".cbr"; private static final String CBR_EXTENSION = ".cbr";
private static final String CB7_EXTENSION = ".cb7"; 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 BookRepository bookRepository;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
@@ -144,6 +144,28 @@ public class FileService {
// IMAGE OPERATIONS // 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) { public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 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 { public static void saveImage(byte[] imageData, String filePath) throws IOException {
BufferedImage originalImage = null; BufferedImage originalImage = null;
try { try {
originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); originalImage = readImage(imageData);
if (originalImage == null) { 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 outputFile = new File(filePath);
File parentDir = outputFile.getParentFile(); File parentDir = outputFile.getParentFile();
@@ -191,13 +214,7 @@ public class FileService {
// Validate and convert // Validate and convert
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) { return readImage(response.getBody());
BufferedImage image = ImageIO.read(inputStream);
if (image == null) {
throw new IOException("Downloaded content is not a supported image format.");
}
return image;
}
} else { } else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
} }
@@ -216,10 +233,11 @@ public class FileService {
validateCoverFile(file); validateCoverFile(file);
BufferedImage originalImage; BufferedImage originalImage;
try (InputStream inputStream = file.getInputStream()) { try (InputStream inputStream = file.getInputStream()) {
originalImage = ImageIO.read(inputStream); originalImage = readImage(inputStream);
} }
if (originalImage == null) { 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); boolean success = saveCoverImages(originalImage, bookId);
if (!success) { if (!success) {
@@ -235,12 +253,10 @@ public class FileService {
public void createThumbnailFromBytes(long bookId, byte[] imageBytes) { public void createThumbnailFromBytes(long bookId, byte[] imageBytes) {
try { try {
BufferedImage originalImage; BufferedImage originalImage = readImage(imageBytes);
try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) {
originalImage = ImageIO.read(inputStream);
}
if (originalImage == null) { 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); boolean success = saveCoverImages(originalImage, bookId);
if (!success) { if (!success) {
@@ -257,6 +273,10 @@ public class FileService {
public void createThumbnailFromUrl(long bookId, String imageUrl) { public void createThumbnailFromUrl(long bookId, String imageUrl) {
try { try {
BufferedImage originalImage = downloadImageFromUrl(imageUrl); BufferedImage originalImage = downloadImageFromUrl(imageUrl);
if (originalImage == null) {
log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId);
return;
}
boolean success = saveCoverImages(originalImage, bookId); boolean success = saveCoverImages(originalImage, bookId);
if (!success) { if (!success) {
throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images");
@@ -355,6 +355,40 @@ class FileServiceTest {
@DisplayName("Image Operations") @DisplayName("Image Operations")
class ImageOperationsTests { class ImageOperationsTests {
@Nested
@DisplayName("readImage")
class ReadImageTests {
@Test
void validData_returnsImage() throws IOException {
BufferedImage image = createTestImage(100, 100);
byte[] imageData = imageToBytes(image);
BufferedImage result = FileService.readImage(imageData);
assertNotNull(result);
assertEquals(100, result.getWidth());
assertEquals(100, result.getHeight());
}
@Test
void nullData_throwsException() {
IOException ex = assertThrows(IOException.class, () -> FileService.readImage((byte[]) null));
assertEquals("Image data is null or empty", ex.getMessage());
}
@Test
void emptyData_throwsException() {
IOException ex = assertThrows(IOException.class, () -> FileService.readImage(new byte[0]));
assertEquals("Image data is null or empty", ex.getMessage());
}
@Test
void invalidData_returnsNull() throws IOException {
byte[] invalidData = "not an image".getBytes();
assertNull(FileService.readImage(invalidData));
}
}
@Nested @Nested
@DisplayName("resizeImage") @DisplayName("resizeImage")
class ResizeImageTests { class ResizeImageTests {
@@ -460,12 +494,13 @@ class FileServiceTest {
} }
@Test @Test
void invalidImageData_throwsException() { void invalidImageData_skipsSave() {
byte[] invalidData = "not an image".getBytes(); byte[] invalidData = "not an image".getBytes();
Path outputPath = tempDir.resolve("invalid.jpg"); Path outputPath = tempDir.resolve("invalid.jpg");
assertThrows(IOException.class, () -> assertDoesNotThrow(() ->
FileService.saveImage(invalidData, outputPath.toString())); FileService.saveImage(invalidData, outputPath.toString()));
assertFalse(Files.exists(outputPath));
} }
@Test @Test
@@ -473,8 +508,9 @@ class FileServiceTest {
byte[] emptyData = new byte[0]; byte[] emptyData = new byte[0];
Path outputPath = tempDir.resolve("empty.jpg"); Path outputPath = tempDir.resolve("empty.jpg");
assertThrows(IOException.class, () -> IOException ex = assertThrows(IOException.class, () ->
FileService.saveImage(emptyData, outputPath.toString())); FileService.saveImage(emptyData, outputPath.toString()));
assertEquals("Image data is null or empty", ex.getMessage());
} }
@Test @Test
@@ -506,8 +542,9 @@ class FileServiceTest {
@Test @Test
void nullImageData_throwsException() { void nullImageData_throwsException() {
Path outputPath = tempDir.resolve("null.jpg"); Path outputPath = tempDir.resolve("null.jpg");
assertThrows(NullPointerException.class, () -> IOException ex = assertThrows(IOException.class, () ->
FileService.saveImage(null, outputPath.toString())); FileService.saveImage(null, outputPath.toString()));
assertEquals("Image data is null or empty", ex.getMessage());
} }
} }
} }
@@ -885,34 +922,28 @@ class FileServiceTest {
} }
@Test @Test
void invalidImageBytes_throwsRuntimeException() { void invalidImageBytes_skipsThumbnail() {
byte[] invalidData = "not an image".getBytes(); byte[] invalidData = "not an image".getBytes();
RuntimeException exception = assertThrows(RuntimeException.class, () -> assertDoesNotThrow(() ->
fileService.createThumbnailFromBytes(16L, invalidData)); fileService.createThumbnailFromBytes(16L, invalidData));
assertTrue(exception.getMessage().contains("Image not found") || assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L))));
exception.getMessage().contains("Failed"),
"Exception message should indicate image processing failure");
} }
@Test @Test
void emptyImageBytes_throwsRuntimeException() { void emptyImageBytes_throwsRuntimeException() {
byte[] emptyData = new byte[0]; byte[] emptyData = new byte[0];
// FileService wraps ImageIO exceptions in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () -> RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromBytes(17L, emptyData)); fileService.createThumbnailFromBytes(17L, emptyData));
assertTrue(exception.getMessage().contains("Image not found") || assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage());
exception.getMessage().contains("Failed"),
"Exception message should indicate image processing failure");
} }
@Test @Test
void nullImageBytes_throwsRuntimeException() { void nullImageBytes_throwsRuntimeException() {
// Null input causes NPE in ByteArrayInputStream constructor, which is caught and wrapped
RuntimeException exception = assertThrows(RuntimeException.class, () -> RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromBytes(18L, null)); fileService.createThumbnailFromBytes(18L, null));
assertNotNull(exception.getMessage(), "Exception should have a message"); assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage());
} }
} }
@@ -1009,18 +1040,15 @@ class FileServiceTest {
} }
@Test @Test
void corruptImageData_throwsRuntimeException() { void corruptImageData_skipsThumbnail() {
// Valid MIME type but corrupt image data // Valid MIME type but corrupt image data
byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); byte[] corruptData = ("not an image but has jpeg mime type").getBytes();
MockMultipartFile corruptFile = new MockMultipartFile( MockMultipartFile corruptFile = new MockMultipartFile(
"file", "corrupt.jpg", "image/jpeg", corruptData); "file", "corrupt.jpg", "image/jpeg", corruptData);
// FileService wraps exceptions in RuntimeException via ApiError assertDoesNotThrow(() ->
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(12L, corruptFile)); fileService.createThumbnailFromFile(12L, corruptFile));
assertTrue(exception.getMessage().contains("Image not found") || assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L))));
exception.getMessage().contains("not readable"),
"Exception message should indicate image processing failure");
} }
@Test @Test
@@ -1209,9 +1237,9 @@ class FileServiceTest {
} }
@Test @Test
@DisplayName("throws exception when ImageIO cannot read bytes") @DisplayName("returns null when ImageIO cannot read bytes")
@Timeout(5) @Timeout(5)
void downloadImageFromUrl_invalidImageData_throwsException() { void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException {
String imageUrl = "http://example.com/image.jpg"; String imageUrl = "http://example.com/image.jpg";
byte[] invalidBytes = "not an image".getBytes(); byte[] invalidBytes = "not an image".getBytes();
ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(invalidBytes); ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(invalidBytes);
@@ -1222,8 +1250,8 @@ class FileServiceTest {
eq(byte[].class) eq(byte[].class)
)).thenReturn(responseEntity); )).thenReturn(responseEntity);
assertThrows(IOException.class, () -> BufferedImage result = fileService.downloadImageFromUrl(imageUrl);
fileService.downloadImageFromUrl(imageUrl)); assertNull(result);
} }
@Test @Test