Yokan / rebuild
Course 1 8624561

EinkPageTranscoder.android.kt

composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.android.kt

implementation46 lines
1package eu.friedcutlet.yokan.services.download23import android.graphics.Bitmap4import android.graphics.BitmapFactory5import android.graphics.Canvas6import android.graphics.ColorMatrix7import android.graphics.ColorMatrixColorFilter8import android.graphics.Paint9import android.graphics.Rect10import eu.friedcutlet.yokan.database.einkScaledSize11import java.io.ByteArrayOutputStream1213internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {14    if (bytes.isGif()) return null15    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }16    BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)17    if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null18    val (width, height) = einkScaledSize(bounds.outWidth, bounds.outHeight, maxShortSide)19    // Power-of-two subsampling keeps peak memory low; the final scale happens while drawing.20    var sample = 121    while (bounds.outWidth / (sample * 2) >= width && bounds.outHeight / (sample * 2) >= height) sample *= 222    val decoded = runCatching {23        BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })24    }.getOrNull() ?: return null25    val target = runCatching { Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) }.getOrNull()26    if (target == null) {27        decoded.recycle()28        return null29    }30    return try {31        val paint = Paint(Paint.FILTER_BITMAP_FLAG).apply {32            colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) })33        }34        Canvas(target).apply {35            drawColor(android.graphics.Color.WHITE)36            drawBitmap(decoded, null, Rect(0, 0, width, height), paint)37        }38        ByteArrayOutputStream().use { out ->39            if (!target.compress(Bitmap.CompressFormat.JPEG, EinkJpegQuality, out)) return null40            out.toByteArray()41        }.takeIf { it.isNotEmpty() && it.size < bytes.size }42    } finally {43        decoded.recycle()44        target.recycle()45    }46}47

Search chapters, reference and source filenames.