package eu.friedcutlet.yokan.services.download import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.Rect import android.media.ExifInterface import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean { if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return false val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) val regions = tallImageRegions(bounds.outWidth, bounds.outHeight, maximumHeight) if (regions.isEmpty()) return false // Splitting must not discard an orientation that the reader would apply to the original. 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 false } val image = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false try { regions.forEachIndexed { index, region -> currentCoroutineContext().ensureActive() val tile = Bitmap.createBitmap(image.width, region.height, Bitmap.Config.ARGB_8888) val encoded = try { Canvas(tile).apply { drawColor(Color.WHITE) drawBitmap(image, Rect(0, region.top, image.width, region.top + region.height), Rect(0, 0, image.width, region.height), null) } ByteArrayOutputStream().use { out -> check(tile.compress(Bitmap.CompressFormat.JPEG, 90, out)) out.toByteArray() } } finally { tile.recycle() } writeTile(index, encoded) } return true } finally { image.recycle() } }