package eu.friedcutlet.yokan.services.download import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.Paint import android.graphics.Rect import eu.friedcutlet.yokan.database.einkScaledSize import java.io.ByteArrayOutputStream internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? { if (bytes.isGif()) return null val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null val (width, height) = einkScaledSize(bounds.outWidth, bounds.outHeight, maxShortSide) // Power-of-two subsampling keeps peak memory low; the final scale happens while drawing. var sample = 1 while (bounds.outWidth / (sample * 2) >= width && bounds.outHeight / (sample * 2) >= height) sample *= 2 val decoded = runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) }.getOrNull() ?: return null val target = runCatching { Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) }.getOrNull() if (target == null) { decoded.recycle() return null } return try { val paint = Paint(Paint.FILTER_BITMAP_FLAG).apply { colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) }) } Canvas(target).apply { drawColor(android.graphics.Color.WHITE) drawBitmap(decoded, null, Rect(0, 0, width, height), paint) } ByteArrayOutputStream().use { out -> if (!target.compress(Bitmap.CompressFormat.JPEG, EinkJpegQuality, out)) return null out.toByteArray() }.takeIf { it.isNotEmpty() && it.size < bytes.size } } finally { decoded.recycle() target.recycle() } }