From 84fe3b72a120d918786f243d0a7cadd8947b75b5 Mon Sep 17 00:00:00 2001 From: Gauthier Roebroeck Date: Mon, 9 Oct 2023 15:57:52 +0800 Subject: [PATCH] feat(komga): prevent image resizing scale up --- .../infrastructure/image/ImageConverter.kt | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/komga/src/main/kotlin/org/gotson/komga/infrastructure/image/ImageConverter.kt b/komga/src/main/kotlin/org/gotson/komga/infrastructure/image/ImageConverter.kt index b0196ce1..d93078dc 100644 --- a/komga/src/main/kotlin/org/gotson/komga/infrastructure/image/ImageConverter.kt +++ b/komga/src/main/kotlin/org/gotson/komga/infrastructure/image/ImageConverter.kt @@ -2,17 +2,22 @@ package org.gotson.komga.infrastructure.image import mu.KotlinLogging import net.coobird.thumbnailator.Thumbnails +import org.gotson.komga.infrastructure.mediacontainer.ContentDetector import org.springframework.stereotype.Service import java.awt.Color import java.awt.image.BufferedImage import java.io.ByteArrayOutputStream import javax.imageio.ImageIO +import kotlin.math.max import kotlin.math.min private val logger = KotlinLogging.logger {} @Service -class ImageConverter { +class ImageConverter( + private val imageAnalyzer: ImageAnalyzer, + private val contentDetector: ContentDetector, +) { val supportedReadFormats by lazy { ImageIO.getReaderFormatNames().toList() } val supportedReadMediaTypes by lazy { ImageIO.getReaderMIMETypes().toList() } @@ -51,9 +56,20 @@ class ImageConverter { } fun resizeImage(imageBytes: ByteArray, format: ImageType, size: Int): ByteArray { + val longestEdge = imageAnalyzer.getDimension(imageBytes.inputStream())?.let { + val mediaType = contentDetector.detectMediaType(imageBytes.inputStream()) + val longestEdge = max(it.height, it.width) + // don't resize if source and target format is the same, and source is smaller than desired + if (mediaType == format.mediaType && longestEdge <= size) return imageBytes + longestEdge + } + + // prevent upscaling + val resizeTo = if (longestEdge != null) min(longestEdge, size) else size + return ByteArrayOutputStream().use { Thumbnails.of(imageBytes.inputStream()) - .size(size, size) + .size(resizeTo, resizeTo) .imageType(BufferedImage.TYPE_INT_ARGB) .outputFormat(format.imageIOFormat) .toOutputStream(it)