gpt4 book ai didi

android - 如何使用 Stock 相机应用程序通过 Jetpack Compose 拍照?

转载 作者:行者123 更新时间:2023-12-05 09:27:23 31 4
gpt4 key购买 nike

在我使用 Jetpack Compose 的应用中,如何使用现有的图库应用拍照并存储? Google 的文档通过使用 Intent 提到了折旧的 Camera API,但他们使用的是旧的 View 系统。似乎较新的 Camera2CameraX API 都旨在直接在应用程序中创建自定义相机界面。

最佳答案

您必须使用 Activity 契约(Contract),请参阅 this article for details

class ComposeFileProvider : FileProvider(
R.xml.filepaths
) {
companion object {
fun getImageUri(context: Context): Uri {
val directory = File(context.cacheDir, "images")
directory.mkdirs()
val file = File.createTempFile(
"selected_image_",
".jpg",
directory,
)
val authority = context.packageName + ".fileprovider"
return getUriForFile(
context,
authority,
file,
)
}
}
}

@Composable
fun ImagePicker(
modifier: Modifier = Modifier,
) {
var hasImage by remember {
mutableStateOf(false)
}
var imageUri by remember {
mutableStateOf<Uri?>(null)
}

val imagePicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
onResult = { uri ->
hasImage = uri != null
imageUri = uri
}
)

val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture(),
onResult = { success ->
hasImage = success
}
)

val context = LocalContext.current
Box(
modifier = modifier,
) {
if (hasImage && imageUri != null) {
AsyncImage(
model = imageUri,
modifier = Modifier.fillMaxWidth(),
contentDescription = "Selected image",
)
}
Column(
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = {
imagePicker.launch("image/*")
},
) {
Text(
text = "Select Image"
)
}
Button(
modifier = Modifier.padding(top = 16.dp),
onClick = {
val uri = ComposeFileProvider.getImageUri(context)
imageUri = uri
cameraLauncher.launch(uri)
},
) {
Text(
text = "Take photo"
)
}
}
}
}

关于android - 如何使用 Stock 相机应用程序通过 Jetpack Compose 拍照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72511469/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com