gpt4 book ai didi

android - 使用 Kotlin 从相机/画廊捕获图像并在 Activity/fragment 中显示

转载 作者:行者123 更新时间:2023-12-04 23:53:35 24 4
gpt4 key购买 nike

我知道这是一个使用 java 很好地回答的微不足道的问题,但我确信有新的 API 可以使事情变得更容易,例如

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
//处理返回的 Uri
}

val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
}
}

val imageUri: Uri = ...
button.setOnClickListener {
takePicture.launch(imageUri)
}

问:如何使用 kotlin 实现上述问题并为此实现最新的 APIs

PS:如果提供的答案贬值或过时,这个问题仍然有效。

最佳答案

这是我的代码,希望对你有帮助

  • 拍照:
  fun takePicture() {
val root =
File(Environment.getExternalStorageDirectory(), BuildConfig.APPLICATION_ID + File.separator)
root.mkdirs()
val fname = "img_" + System.currentTimeMillis() + ".jpg"
val sdImageMainDirectory = File(root, fname)
viewModel.profileImageUri = FileProvider.getUriForFile(requireContext(), context?.applicationContext?.packageName + ".provider", sdImageMainDirectory)
takePicture.launch(viewModel.profileImageUri)
}

val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
Picasso.get().load(viewModel.profileImageUri).resize(800,800).into(registerImgAvatar)
}
}

  • 从图书馆中选择
    private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()){ uri: Uri? ->
uri?.let { it ->
// The image was saved into the given Uri -> do something with it
Picasso.get().load(it).resize(800,800).into(registerImgAvatar)
}
}

然后在按下按钮时调用函数:

btnSelectFromGallery.setOnClickListener {
pickImages.launch("image/*")
}
btnTakePicture.setOnClickListener {
takePicture()
}

关于android - 使用 Kotlin 从相机/画廊捕获图像并在 Activity/fragment 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62387789/

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