Yokan / rebuild
Course 1 8624561

TallImageSplitter.android.kt

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

implementation44 lines
1package eu.friedcutlet.yokan.services.download23import android.graphics.Bitmap4import android.graphics.BitmapFactory5import android.graphics.Canvas6import android.graphics.Color7import android.graphics.Rect8import android.media.ExifInterface9import java.io.ByteArrayInputStream10import java.io.ByteArrayOutputStream11import kotlinx.coroutines.currentCoroutineContext12import kotlinx.coroutines.ensureActive1314internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean {15    if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return false16    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }17    BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)18    val regions = tallImageRegions(bounds.outWidth, bounds.outHeight, maximumHeight)19    if (regions.isEmpty()) return false20    // Splitting must not discard an orientation that the reader would apply to the original.21    if (bytes.size >= 2 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte()) {22        val orientation = ByteArrayInputStream(bytes).use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) }23        if (orientation != ExifInterface.ORIENTATION_NORMAL && orientation != ExifInterface.ORIENTATION_UNDEFINED) return false24    }25    val image = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false26    try {27        regions.forEachIndexed { index, region ->28            currentCoroutineContext().ensureActive()29            val tile = Bitmap.createBitmap(image.width, region.height, Bitmap.Config.ARGB_8888)30            val encoded = try {31                Canvas(tile).apply {32                    drawColor(Color.WHITE)33                    drawBitmap(image, Rect(0, region.top, image.width, region.top + region.height), Rect(0, 0, image.width, region.height), null)34                }35                ByteArrayOutputStream().use { out ->36                    check(tile.compress(Bitmap.CompressFormat.JPEG, 90, out))37                    out.toByteArray()38                }39            } finally { tile.recycle() }40            writeTile(index, encoded)41        }42        return true43    } finally { image.recycle() }44}45

Search chapters, reference and source filenames.