I want to show thumbnails of images and cache comp...
# compose-desktop
t
I want to show thumbnails of images and cache compressed version of the thumbnails. My fastest approach yet uses Skia to load and scale the image. But to compress the image i have to use ImageIO.write because skia bindings do not support encoding of ImageAsset objects. Any ideas how to improve this?
Here is the current code:
Copy code
val jpegSizeCache: MutableMap<String, ByteArray> = mutableMapOf()

suspend fun loadImageSizeFileCached(file: File, width: Int) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val key = "${file.absolutePath}:$width"
    val cachedData = jpegSizeCache[key]
    if (cachedData == null) {
        val fullImage = Image.makeFromEncoded(file.readBytes())
        val ratio = fullImage.width.toFloat() / fullImage.height.toFloat()
        val height = (width.toFloat() / ratio).roundToInt()
        val asset = fullImage.toScaledImageAsset(width, height)
        // compress data to jpeg for caching
        val scaledImage = BufferedImage(asset.width, asset.height, BufferedImage.TYPE_INT_RGB)
        val intArray = (scaledImage.raster.dataBuffer as DataBufferInt).data
        asset.readPixels(intArray)
        val baos = ByteArrayOutputStream()
        ImageIO.write(scaledImage, "jpeg", baos)
        val bytes = baos.toByteArray()
        jpegSizeCache[key] = bytes
        asset
    } else {
        Image.makeFromEncoded(cachedData).toImageAsset()
    }
}

suspend fun Image.toScaledImageAsset(width: Int, height: Int): ImageAsset = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val bitmap = Bitmap()
    bitmap.allocPixels(ImageInfo.makeN32(width, height, ColorAlphaType.PREMUL))
    val canvas = Canvas(bitmap)
    val paint = Paint().apply {
        filterQuality = FilterQuality.HIGH
    }
    canvas.drawImageRect(this@toScaledImageAsset, Rect(0f, 0f, width.toFloat(), height.toFloat()), paint)
    bitmap.setImmutable()
    bitmap.asImageAsset()
}