package eu.friedcutlet.yokan.ui.screens.reader import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.media.ExifInterface import eu.friedcutlet.yokan.services.download.MaxSplitImageBytes import eu.friedcutlet.yokan.services.download.MaxSplitImagePixels import eu.friedcutlet.yokan.services.download.mayBeAnimatedImage import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream internal actual suspend fun mergeSpreadImages(left: ByteArray, right: ByteArray): ByteArray? { val first = decodeSpreadPage(left) ?: return null try { val second = decodeSpreadPage(right) ?: return null try { val layout = spreadLayout(first.width, first.height, second.width, second.height) ?: return null val output = Bitmap.createBitmap(layout.width, layout.height, Bitmap.Config.ARGB_8888) try { val paint = Paint(Paint.FILTER_BITMAP_FLAG) Canvas(output).apply { drawColor(Color.WHITE) drawBitmap(first, null, Rect(0, 0, layout.leftWidth, layout.height), paint) drawBitmap(second, null, Rect(layout.leftWidth, 0, layout.width, layout.height), paint) } return ByteArrayOutputStream().use { out -> check(output.compress(Bitmap.CompressFormat.JPEG, 90, out)) out.toByteArray() } } finally { output.recycle() } } finally { second.recycle() } } finally { first.recycle() } } /** Same limits as tall-image splitting: bounded input, still image, upright EXIF orientation. */ private fun decodeSpreadPage(bytes: ByteArray): Bitmap? { if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return null val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) if (bounds.outWidth <= 0 || bounds.outHeight <= 0 || bounds.outWidth.toLong() * bounds.outHeight > MaxSplitImagePixels) return null if (bytes.size >= 2 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte()) { val orientation = ByteArrayInputStream(bytes).use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) } if (orientation != ExifInterface.ORIENTATION_NORMAL && orientation != ExifInterface.ORIENTATION_UNDEFINED) return null } return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }