feat(komga): prevent image resizing scale up

This commit is contained in:
Gauthier Roebroeck 2023-10-09 15:57:52 +08:00
parent 5fa789b8d8
commit 84fe3b72a1

View file

@ -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)