SpreadMerge.android.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/SpreadMerge.android.kt
1package eu.friedcutlet.yokan.ui.screens.reader23import android.graphics.Bitmap4import android.graphics.BitmapFactory5import android.graphics.Canvas6import android.graphics.Color7import android.graphics.Paint8import android.graphics.Rect9import android.media.ExifInterface10import eu.friedcutlet.yokan.services.download.MaxSplitImageBytes11import eu.friedcutlet.yokan.services.download.MaxSplitImagePixels12import eu.friedcutlet.yokan.services.download.mayBeAnimatedImage13import java.io.ByteArrayInputStream14import java.io.ByteArrayOutputStream1516internal actual suspend fun mergeSpreadImages(left: ByteArray, right: ByteArray): ByteArray? {17 val first = decodeSpreadPage(left) ?: return null18 try {19 val second = decodeSpreadPage(right) ?: return null20 try {21 val layout = spreadLayout(first.width, first.height, second.width, second.height) ?: return null22 val output = Bitmap.createBitmap(layout.width, layout.height, Bitmap.Config.ARGB_8888)23 try {24 val paint = Paint(Paint.FILTER_BITMAP_FLAG)25 Canvas(output).apply {26 drawColor(Color.WHITE)27 drawBitmap(first, null, Rect(0, 0, layout.leftWidth, layout.height), paint)28 drawBitmap(second, null, Rect(layout.leftWidth, 0, layout.width, layout.height), paint)29 }30 return ByteArrayOutputStream().use { out ->31 check(output.compress(Bitmap.CompressFormat.JPEG, 90, out))32 out.toByteArray()33 }34 } finally { output.recycle() }35 } finally { second.recycle() }36 } finally { first.recycle() }37}3839/** Same limits as tall-image splitting: bounded input, still image, upright EXIF orientation. */40private fun decodeSpreadPage(bytes: ByteArray): Bitmap? {41 if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return null42 val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }43 BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)44 if (bounds.outWidth <= 0 || bounds.outHeight <= 0 || bounds.outWidth.toLong() * bounds.outHeight > MaxSplitImagePixels) return null45 if (bytes.size >= 2 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte()) {46 val orientation = ByteArrayInputStream(bytes).use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) }47 if (orientation != ExifInterface.ORIENTATION_NORMAL && orientation != ExifInterface.ORIENTATION_UNDEFINED) return null48 }49 return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)50}51