Skip to content

Instantly share code, notes, and snippets.

@oussama-dz
Last active June 22, 2023 07:15
Show Gist options
  • Select an option

  • Save oussama-dz/eca3ba199ad58c7c317c51b17824e94a to your computer and use it in GitHub Desktop.

Select an option

Save oussama-dz/eca3ba199ad58c7c317c51b17824e94a to your computer and use it in GitHub Desktop.
Integrating local storage with the image picker.
@Composable
fun ImagePicker() {
var imageUri: Uri? by remember { mutableStateOf(null) }
val context = LocalContext.current
val dataStore = remember { StoreData() }
val scope = rememberCoroutineScope()
val launcher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenDocument()) {
it?.let { uri ->
context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION )
scope.launch {
dataStore.storeImage(context, uri.toString())
}
}
}
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)
) {
AsyncImage(
model = imageUri,
contentDescription = null,
modifier = Modifier
.size(200.dp),
contentScale = ContentScale.Crop
)
Button(
onClick = {
launcher.launch(arrayOf("image/*"))
}
) {
Text(text = "Pick Image")
}
}
LaunchedEffect(key1 = true) {
dataStore.getImage(context).collect {
if (it != null)
imageUri = Uri.parse(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment