使用Kotlin从相机/画廊捕获图像并在活动/片段中显示 [英] Capture Image from Camera/Gallery and Display in Activity/Fragment using Kotlin

查看:194
本文介绍了使用Kotlin从相机/画廊捕获图像并在活动/片段中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个简单的问题,使用Java可以很好地解决,但是我确定有新的 API 可以使事情变得更容易,例如

i know this is a trivial question well answered using java, but i'm sure there are new APIs to make things easier such as

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实现上述问题并为此实现最新的 API

Q: How to implement the above question using kotlin and implementing the lastest APIs for that

PS:如果提供的答案变得过时或过时,此问题仍然有效.

PS: this is question is still valid if answers provided become depreciated or obsolete.

推荐答案

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

Here is my code, hope this help

  • 拍照:
  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)
                }
            }
    
    

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

    Then call the function when press button:

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

    这篇关于使用Kotlin从相机/画廊捕获图像并在活动/片段中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆