contacts: high res contact photos & cropping #221 #220
- Commit
7e6c35d2bb65a8a8813eb86bb2c22f244009dcff- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-14 23:21 UTC (5 months ago)
- Parents
21d0938
Diff
contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.ktindex 8637bcb005..a49b808062 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt@@ -295,6 +295,18 @@ fun Navigation(viewModel: ContactViewModel, initialRoute: Route? = null) { entry<Route.AddToGroupDialog>(metadata = DialogPage()) { key -> AddToGroupDialog(viewModel, key.contactIds) { backStack.pop() } }++ entry<Route.CropPhoto>(metadata = ListDetailPage()) { key ->+ val decodedUri = java.net.URLDecoder.decode(key.uri, "UTF-8")+ CropPhotoScreen(+ uri = decodedUri,+ onCropComplete = { bitmap ->+ viewModel.setEditDraftPhotoFromBitmap(bitmap)+ backStack.pop()+ },+ onCancel = { backStack.pop() }+ )+ } } } @@ -333,4 +345,7 @@ sealed interface Route: NavKey { @Serializable object AddAccountDialog : Route++ @Serializable+ data class CropPhoto(val uri: String) : Route }
contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.ktindex a887679a42..e16788cf80 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt@@ -493,6 +493,7 @@ fun getDetailsInternal(context: Context, id: Long? = null, isProfile: Boolean = ContactsContract.Data.RAW_CONTACT_ID, ContactsContract.Data._ID, ContactsContract.Data.MIMETYPE,+ ContactsContract.Data.CONTACT_ID, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA3,@@ -540,6 +541,7 @@ fun getDetailsInternal(context: Context, id: Long? = null, isProfile: Boolean = val d8Idx = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA8) val d9Idx = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA9) val d10Idx = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA10)+ val contactIdIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID) val d15Idx = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA15) while (cursor.moveToNext()) {@@ -591,9 +593,16 @@ fun getDetailsInternal(context: Context, id: Long? = null, isProfile: Boolean = } } CDKPhoto.CONTENT_ITEM_TYPE -> {- val photoBlob = cursor.getBlobOrNull(d15Idx)- if (photoBlob != null) {- photosMap.getOrPut(rawId) { mutableListOf() }.add(Photo(dataId, Base64.encode(photoBlob)))+ val contactId = cursor.getLong(contactIdIdx)+ val contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId)+ val fullSizeStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, contactUri, true)+ val photoBytes = if (fullSizeStream != null) {+ fullSizeStream.use { it.readBytes() }+ } else {+ cursor.getBlobOrNull(d15Idx)+ }+ if (photoBytes != null) {+ photosMap.getOrPut(rawId) { mutableListOf() }.add(Photo(dataId, Base64.encode(photoBytes))) } } CDKSName.CONTENT_ITEM_TYPE -> {
contacts/src/main/java/com/vayunmathur/contacts/ui/CropPhotoScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/CropPhotoScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/CropPhotoScreen.ktnew file mode 100644index 0000000000..c3e08ba13b--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/CropPhotoScreen.kt@@ -0,0 +1,302 @@+package com.vayunmathur.contacts.ui++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.net.Uri+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathFillType+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlin.math.min+import kotlin.math.roundToInt++private enum class DragHandle {+ TopLeft, Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, Move, None+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun CropPhotoScreen(+ uri: String,+ onCropComplete: (Bitmap) -> Unit,+ onCancel: () -> Unit+) {+ val context = LocalContext.current+ var bitmap by remember { mutableStateOf<Bitmap?>(null) }++ var cropOffset by remember { mutableStateOf(Offset.Zero) }+ var cropSize by remember { mutableFloatStateOf(0f) }+ var imgDisplayOffset by remember { mutableStateOf(Offset.Zero) }+ var imgDisplayW by remember { mutableFloatStateOf(0f) }+ var imgDisplayH by remember { mutableFloatStateOf(0f) }+ var initialized by remember { mutableStateOf(false) }++ LaunchedEffect(uri) {+ bitmap = withContext(Dispatchers.IO) {+ try {+ val parsed = Uri.parse(uri)+ context.contentResolver.openInputStream(parsed)?.use { stream ->+ BitmapFactory.decodeStream(stream)+ }+ } catch (_: Exception) { null }+ }+ }++ DisposableEffect(Unit) {+ onDispose { bitmap?.recycle() }+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("Crop Photo") },+ navigationIcon = {+ TextButton(onClick = onCancel) { Text("Cancel") }+ },+ actions = {+ TextButton(onClick = {+ val bmp = bitmap ?: return@TextButton+ if (imgDisplayW <= 0f || imgDisplayH <= 0f) return@TextButton++ val scaleX = bmp.width.toFloat() / imgDisplayW+ val scaleY = bmp.height.toFloat() / imgDisplayH+ val cx = ((cropOffset.x - imgDisplayOffset.x) * scaleX).roundToInt()+ .coerceIn(0, bmp.width - 1)+ val cy = ((cropOffset.y - imgDisplayOffset.y) * scaleY).roundToInt()+ .coerceIn(0, bmp.height - 1)+ val cs = (cropSize * scaleX).roundToInt()+ .coerceIn(1, min(bmp.width - cx, bmp.height - cy))++ val cropped = Bitmap.createBitmap(bmp, cx, cy, cs, cs)+ val scaled = Bitmap.createScaledBitmap(cropped, 1024, 1024, true)+ if (cropped !== scaled) cropped.recycle()+ onCropComplete(scaled)+ }) { Text("Done") }+ }+ )+ }+ ) { padding ->+ val currentBitmap = bitmap ?: return@Scaffold++ BoxWithConstraints(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .background(Color.Black),+ contentAlignment = Alignment.Center+ ) {+ val maxW = constraints.maxWidth.toFloat()+ val maxH = constraints.maxHeight.toFloat()++ val scale = (maxW / currentBitmap.width).coerceAtMost(maxH / currentBitmap.height)+ val imgW = currentBitmap.width * scale+ val imgH = currentBitmap.height * scale+ val imgOffsetX = (maxW - imgW) / 2f+ val imgOffsetY = (maxH - imgH) / 2f++ imgDisplayW = imgW+ imgDisplayH = imgH+ imgDisplayOffset = Offset(imgOffsetX, imgOffsetY)++ if (!initialized) {+ val initSize = min(imgW, imgH) * 0.8f+ cropSize = initSize+ cropOffset = Offset((maxW - initSize) / 2f, (maxH - initSize) / 2f)+ initialized = true+ }++ var activeDragHandle by remember { mutableStateOf(DragHandle.None) }+ val handleTouchRadius = with(LocalDensity.current) { 24.dp.toPx() }+ val minCropSize = with(LocalDensity.current) { 80.dp.toPx() }++ val imageBitmap = remember(currentBitmap) { currentBitmap.asImageBitmap() }++ Canvas(+ modifier = Modifier+ .fillMaxSize()+ .pointerInput(Unit) {+ detectDragGestures(+ onDragStart = { pos ->+ val handlePositions = mapOf(+ DragHandle.TopLeft to cropOffset,+ DragHandle.Top to Offset(cropOffset.x + cropSize / 2f, cropOffset.y),+ DragHandle.TopRight to Offset(cropOffset.x + cropSize, cropOffset.y),+ DragHandle.Right to Offset(cropOffset.x + cropSize, cropOffset.y + cropSize / 2f),+ DragHandle.BottomRight to Offset(cropOffset.x + cropSize, cropOffset.y + cropSize),+ DragHandle.Bottom to Offset(cropOffset.x + cropSize / 2f, cropOffset.y + cropSize),+ DragHandle.BottomLeft to Offset(cropOffset.x, cropOffset.y + cropSize),+ DragHandle.Left to Offset(cropOffset.x, cropOffset.y + cropSize / 2f)+ )++ val nearest = handlePositions.minByOrNull { (pos - it.value).getDistance() }+ activeDragHandle = if (nearest != null && (pos - nearest.value).getDistance() <= handleTouchRadius) {+ nearest.key+ } else {+ val cropRect = Rect(cropOffset.x, cropOffset.y, cropOffset.x + cropSize, cropOffset.y + cropSize)+ if (cropRect.contains(pos)) DragHandle.Move else DragHandle.None+ }+ },+ onDrag = { change, _ ->+ change.consume()+ val pos = change.position+ when (activeDragHandle) {+ DragHandle.Move -> {+ val delta = change.position - change.previousPosition+ val newX = (cropOffset.x + delta.x).coerceIn(imgOffsetX, imgOffsetX + imgW - cropSize)+ val newY = (cropOffset.y + delta.y).coerceIn(imgOffsetY, imgOffsetY + imgH - cropSize)+ cropOffset = Offset(newX, newY)+ }+ DragHandle.BottomRight -> {+ val anchorX = cropOffset.x+ val anchorY = cropOffset.y+ val newSize = maxOf(pos.x - anchorX, pos.y - anchorY)+ .coerceIn(minCropSize, minOf(imgOffsetX + imgW - anchorX, imgOffsetY + imgH - anchorY))+ cropSize = newSize+ }+ DragHandle.TopLeft -> {+ val anchorX = cropOffset.x + cropSize+ val anchorY = cropOffset.y + cropSize+ val newSize = maxOf(anchorX - pos.x, anchorY - pos.y)+ .coerceIn(minCropSize, minOf(anchorX - imgOffsetX, anchorY - imgOffsetY))+ cropOffset = Offset(anchorX - newSize, anchorY - newSize)+ cropSize = newSize+ }+ DragHandle.TopRight -> {+ val anchorX = cropOffset.x+ val anchorY = cropOffset.y + cropSize+ val newSize = maxOf(pos.x - anchorX, anchorY - pos.y)+ .coerceIn(minCropSize, minOf(imgOffsetX + imgW - anchorX, anchorY - imgOffsetY))+ cropOffset = Offset(anchorX, anchorY - newSize)+ cropSize = newSize+ }+ DragHandle.BottomLeft -> {+ val anchorX = cropOffset.x + cropSize+ val anchorY = cropOffset.y+ val newSize = maxOf(anchorX - pos.x, pos.y - anchorY)+ .coerceIn(minCropSize, minOf(anchorX - imgOffsetX, imgOffsetY + imgH - anchorY))+ cropOffset = Offset(anchorX - newSize, anchorY)+ cropSize = newSize+ }+ DragHandle.Right -> {+ val left = cropOffset.x+ val centerY = cropOffset.y + cropSize / 2f+ val newSize = (pos.x - left)+ .coerceIn(minCropSize, imgOffsetX + imgW - left)+ val newTop = (centerY - newSize / 2f).coerceAtLeast(imgOffsetY)+ val adjustedSize = minOf(newSize, imgOffsetY + imgH - newTop)+ cropOffset = Offset(left, newTop)+ cropSize = adjustedSize+ }+ DragHandle.Left -> {+ val right = cropOffset.x + cropSize+ val centerY = cropOffset.y + cropSize / 2f+ val newSize = (right - pos.x)+ .coerceIn(minCropSize, right - imgOffsetX)+ val newTop = (centerY - newSize / 2f).coerceAtLeast(imgOffsetY)+ val adjustedSize = minOf(newSize, imgOffsetY + imgH - newTop)+ cropOffset = Offset(right - adjustedSize, newTop)+ cropSize = adjustedSize+ }+ DragHandle.Bottom -> {+ val top = cropOffset.y+ val centerX = cropOffset.x + cropSize / 2f+ val newSize = (pos.y - top)+ .coerceIn(minCropSize, imgOffsetY + imgH - top)+ val newLeft = (centerX - newSize / 2f).coerceAtLeast(imgOffsetX)+ val adjustedSize = minOf(newSize, imgOffsetX + imgW - newLeft)+ cropOffset = Offset(newLeft, top)+ cropSize = adjustedSize+ }+ DragHandle.Top -> {+ val bottom = cropOffset.y + cropSize+ val centerX = cropOffset.x + cropSize / 2f+ val newSize = (bottom - pos.y)+ .coerceIn(minCropSize, bottom - imgOffsetY)+ val newLeft = (centerX - newSize / 2f).coerceAtLeast(imgOffsetX)+ val adjustedSize = minOf(newSize, imgOffsetX + imgW - newLeft)+ cropOffset = Offset(newLeft, bottom - adjustedSize)+ cropSize = adjustedSize+ }+ DragHandle.None -> {}+ }+ },+ onDragEnd = { activeDragHandle = DragHandle.None }+ )+ }+ ) {+ drawImage(+ image = imageBitmap,+ srcOffset = IntOffset.Zero,+ srcSize = IntSize(currentBitmap.width, currentBitmap.height),+ dstOffset = IntOffset(imgOffsetX.roundToInt(), imgOffsetY.roundToInt()),+ dstSize = IntSize(imgW.roundToInt(), imgH.roundToInt())+ )++ val cropCenter = Offset(cropOffset.x + cropSize / 2f, cropOffset.y + cropSize / 2f)+ val radius = cropSize / 2f++ val overlayPath = Path().apply {+ addRect(Rect(0f, 0f, maxW, maxH))+ addOval(Rect(cropCenter.x - radius, cropCenter.y - radius, cropCenter.x + radius, cropCenter.y + radius))+ fillType = PathFillType.EvenOdd+ }+ drawPath(overlayPath, Color.Black.copy(alpha = 0.6f))++ drawRect(+ color = Color.White,+ topLeft = cropOffset,+ size = Size(cropSize, cropSize),+ style = Stroke(width = 2.dp.toPx())+ )++ val handleRadius = 6.dp.toPx()+ val handles = listOf(+ cropOffset,+ Offset(cropOffset.x + cropSize / 2f, cropOffset.y),+ Offset(cropOffset.x + cropSize, cropOffset.y),+ Offset(cropOffset.x + cropSize, cropOffset.y + cropSize / 2f),+ Offset(cropOffset.x + cropSize, cropOffset.y + cropSize),+ Offset(cropOffset.x + cropSize / 2f, cropOffset.y + cropSize),+ Offset(cropOffset.x, cropOffset.y + cropSize),+ Offset(cropOffset.x, cropOffset.y + cropSize / 2f)+ )+ handles.forEach { pos ->+ drawCircle(Color.White, radius = handleRadius, center = pos)+ }+ }+ }+ }+}
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex 69de42c3ad..f285bb8c67 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -108,7 +108,8 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> if (uri != null) {- viewModel.setEditDraftPhotoFromUri(uri)+ val encoded = java.net.URLEncoder.encode(uri.toString(), "UTF-8")+ backStack.add(Route.CropPhoto(encoded)) } }
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 9c8cd46200..e525f1bf59 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -533,6 +533,22 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) * and the draft is left unchanged so the picker callback never blocks the * UI thread (large gallery photos can take 100+ ms to decode). */+ fun setEditDraftPhotoFromBitmap(bitmap: Bitmap) {+ viewModelScope.launch(Dispatchers.IO) {+ val scaled = if (bitmap.width != 1024 || bitmap.height != 1024) {+ Bitmap.createScaledBitmap(bitmap, 1024, 1024, true)+ } else bitmap+ val baos = okio.Buffer()+ scaled.compress(Bitmap.CompressFormat.JPEG, 100, baos.outputStream())+ val encoded = android.util.Base64.encodeToString(baos.readByteArray(), android.util.Base64.NO_WRAP)+ updateEditDraft { draft ->+ val newPhoto = draft.photo?.withValue(encoded)+ ?: com.vayunmathur.contacts.data.Photo(0, encoded)+ draft.copy(photo = newPhoto)+ }+ }+ }+ fun setEditDraftPhotoFromUri(uri: android.net.Uri) { viewModelScope.launch(Dispatchers.IO) { try {@@ -540,7 +556,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) val bytes = ctx.contentResolver.openInputStream(uri)?.use { input -> val bitmap = BitmapFactory.decodeStream(input) ?: return@launch- val scaled = bitmap.scale(500, 500)+ val scaled = bitmap.scale(1024, 1024) val baos = okio.Buffer() scaled.compress(Bitmap.CompressFormat.JPEG, 100, baos.outputStream()) val encoded = android.util.Base64.encodeToString(baos.readByteArray(), android.util.Base64.NO_WRAP)