EinkPageTranscoder.skiko.kt
composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.skiko.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.einkScaledSize4import org.jetbrains.skia.ColorAlphaType5import org.jetbrains.skia.ColorType6import org.jetbrains.skia.EncodedImageFormat7import org.jetbrains.skia.FilterMipmap8import org.jetbrains.skia.FilterMode9import org.jetbrains.skia.Image10import org.jetbrains.skia.ImageInfo11import org.jetbrains.skia.MipmapMode12import org.jetbrains.skia.Rect13import org.jetbrains.skia.Surface1415internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {16 if (bytes.isGif()) return null17 // Skia objects are not AutoCloseable on every target, so they are closed explicitly.18 val image = runCatching { Image.makeFromEncoded(bytes) }.getOrNull() ?: return null19 val encoded: ByteArray? = try {20 val (width, height) = einkScaledSize(image.width, image.height, maxShortSide)21 // A GRAY_8 target converts to luminance while drawing and encodes a single-channel JPEG.22 val surface = Surface.makeRaster(ImageInfo(width, height, ColorType.GRAY_8, ColorAlphaType.OPAQUE))23 try {24 surface.canvas.clear(org.jetbrains.skia.Color.WHITE)25 surface.canvas.drawImageRect(26 image,27 Rect.makeWH(image.width.toFloat(), image.height.toFloat()),28 Rect.makeWH(width.toFloat(), height.toFloat()),29 FilterMipmap(FilterMode.LINEAR, MipmapMode.LINEAR),30 null,31 true,32 )33 val snapshot = surface.makeImageSnapshot()34 try {35 snapshot.encodeToData(EncodedImageFormat.JPEG, EinkJpegQuality)?.bytes36 } finally {37 snapshot.close()38 }39 } finally {40 surface.close()41 }42 } catch (_: Exception) {43 null44 } finally {45 image.close()46 }47 return encoded?.takeIf { it.isNotEmpty() && it.size < bytes.size }48}49