[英]Capture Image from Camera/Gallery and Display in Activity/Fragment using Kotlin
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我知道这是一个使用 java 很好回答的微不足道的问题,但我确信有新的
APIs
可以让事情变得更容易,例如
val getContent = registerForActivityResult(GetContent()) { uri: Uri? -> // Handle the returned Uri }
and和
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)
}
Q: How to implement the above question using kotlin and implementing the lastest APIs
for that问:如何使用 kotlin 实现上述问题并为此实现最新的
APIs
PS: this is question is still valid if answers provided become depreciated or obsolete. PS:如果提供的答案已贬值或过时,这个问题仍然有效。
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:然后按下按钮时调用 function:
btnSelectFromGallery.setOnClickListener {
pickImages.launch("image/*")
}
btnTakePicture.setOnClickListener {
takePicture()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.