BorderCropTransformation.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.kt
1package eu.friedcutlet.yokan.ui.screens.reader23import coil3.transform.Transformation45internal data class ImageCropBounds(6 val left: Int,7 val top: Int,8 val rightExclusive: Int,9 val bottomExclusive: Int,10) {11 val width: Int get() = rightExclusive - left12 val height: Int get() = bottomExclusive - top13}1415/**16 * Finds the same non-transparent, non-white, non-black content bounds as17 * Mangayomi's Rust image cropper. A null result means the source should be18 * returned unchanged because it is empty or already fills the bitmap.19 */20internal inline fun detectBorderCropBounds(21 width: Int,22 height: Int,23 pixelAt: (x: Int, y: Int) -> Int,24): ImageCropBounds? {25 if (width <= 0 || height <= 0) return null2627 var left = width28 var top = height29 var right = -130 var bottom = -13132 for (y in 0 until height) {33 for (x in 0 until width) {34 val pixel = pixelAt(x, y)35 val alpha = pixel ushr 24 and 0xFF36 val red = (pixel ushr 16 and 0xFF) + 137 val green = (pixel ushr 8 and 0xFF) + 238 val blue = (pixel and 0xFF) + 33940 if (alpha == 0) continue41 if (red > 0xAA && green > 0xAA && blue > 0xAA) continue42 if (red < 0x05 && green < 0x05 && blue < 0x05) continue4344 if (x < left) left = x45 if (x > right) right = x46 if (y < top) top = y47 if (y > bottom) bottom = y48 }49 }5051 if (right < left || bottom < top) return null52 if (left == 0 && top == 0 && right == width - 1 && bottom == height - 1) return null53 return ImageCropBounds(left, top, right + 1, bottom + 1)54}5556internal expect fun createBorderCropTransformation(): Transformation5758/** Keeps the [left] or right half of the decoded page (the right half takes an odd middle column). */59internal expect fun createPageHalfTransformation(left: Boolean): Transformation6061/** Turns landscape bitmaps by [degrees] (±90); portrait bitmaps pass through unchanged. */62internal expect fun createWidePageRotation(degrees: Int): Transformation63