How can i parse Uri String for loading image from gallery in jetpack compose with Coil?
Asked Answered
D

1

5

Let say i have image components can show image from selected image from gallery;

@Composable
fun ClickableToGalleryImage() {
    var imageUri by remember {
        mutableStateOf<Uri?>(null)
    }
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        println(imageUri)
        imageUri = uri
    }
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Image(
            painter = rememberAsyncImagePainter(
                ImageRequest
                    .Builder(LocalContext.current)
                    .data(data = imageUri)
                    .build()
            ),
            contentDescription = null,
            modifier = Modifier
                .clickable { launcher.launch("image/*") }
                .size(100.dp)
                .clip(CircleShape)
                .border(2.dp, Color.Gray, CircleShape),
            contentScale = ContentScale.Crop
        )
    }
}

this works very well.

But if i extract the imageUri value;

I/System.out: content://com.android.providers.media.documents/document/image%3A33

and manually type the imageUri variable;

Image(
        painter = rememberAsyncImagePainter(
            ImageRequest
                .Builder(LocalContext.current)
                .data(data = "content://com.android.providers.media.documents/document/image%3A33")
                .build()
        ),
        contentDescription = null,
        modifier = Modifier
            .size(100.dp)
            .clip(CircleShape)
            .border(2.dp, Color.Gray, CircleShape),
        contentScale = ContentScale.Crop
    )

Coil can't load picture. Why is that? And how can i show picture from gallery with uri?

Deloris answered 27/5, 2022 at 12:44 Comment(0)
F
6

Coil can't load picture. Why is that?

You do not have read permission to access the content.

And how can i show picture from gallery with uri?

Use the Uri that you get back from your ActivityResultContracts.GetContent request, in the same activity where you requested it.

If you need durable access to the content, switch to OpenDocument and call takePersistableUriPermission() on a ContentResolver, supplying the Uri.

Flamen answered 27/5, 2022 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.