60 lines
2.2 KiB
Kotlin
60 lines
2.2 KiB
Kotlin
package com.inspection.camera.util
|
|
|
|
import android.content.Context
|
|
import android.graphics.Bitmap
|
|
import android.graphics.BitmapFactory
|
|
import android.graphics.Canvas
|
|
import android.graphics.Paint
|
|
import android.graphics.Rect
|
|
import android.net.Uri
|
|
|
|
object PuzzleMerge {
|
|
// Merge up to 4 images into a single 2x2 bitmap
|
|
fun mergeToBitmap(context: Context, imageUris: List<Uri>, targetSize: Int = 1000): Bitmap? {
|
|
if (imageUris.isEmpty()) return null
|
|
val size = targetSize
|
|
val half = size / 2
|
|
val merged = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
|
val canvas = Canvas(merged)
|
|
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
|
|
|
val targets = arrayOf(
|
|
Rect(0, 0, half, half), // TL
|
|
Rect(half, 0, size, half), // TR
|
|
Rect(0, half, half, size), // BL
|
|
Rect(half, half, size, size) // BR
|
|
)
|
|
|
|
val toUse = imageUris.take(4)
|
|
for (i in toUse.indices) {
|
|
val bmp = loadBitmap(context, toUse[i], half, half)
|
|
if (bmp != null) {
|
|
val scaled = Bitmap.createScaledBitmap(bmp, half, half, true)
|
|
canvas.drawBitmap(scaled, null, targets[i], paint)
|
|
bmp.recycle()
|
|
scaled.recycle()
|
|
}
|
|
}
|
|
|
|
// Optional: fill empty cells with placeholder color if needed
|
|
return merged
|
|
}
|
|
|
|
// Load bitmap from URI with sampling to fit within maxW x maxH
|
|
private fun loadBitmap(context: Context, uri: Uri, maxW: Int, maxH: Int): Bitmap? {
|
|
return try {
|
|
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|
context.contentResolver.openInputStream(uri).use { ins ->
|
|
BitmapFactory.decodeStream(ins, null, opts)
|
|
}
|
|
val inSample = maxOf(1, maxOf(opts.outWidth / maxW, opts.outHeight / maxH))
|
|
val opts2 = BitmapFactory.Options().apply { inSampleSize = inSample }
|
|
context.contentResolver.openInputStream(uri).use { ins ->
|
|
BitmapFactory.decodeStream(ins, null, opts2)
|
|
}
|
|
} catch (e: Exception) {
|
|
null
|
|
}
|
|
}
|
|
}
|