使用ActivityResultContracts.getContent()将图像保存到内部存储中。 - (kotlin/java/android)

发布于 2025-01-28 13:31:33 字数 460 浏览 1 评论 0原文

我是新来的文件存储。我的主要目的是用相机拍照,以质量良好存储,然后将其显示在ImageView中。我想避免要求使用用户许可(使用相机和外部存储),并希望使其尽可能简单。

要拍照,我正在使用

val CapturePicture = registerForactivityResult(activeResultContracts.takePicture()){it:boolean--> }。 我不知道如何从此功能或是否应该从此功能中获取位图。据我了解,我应该在调用CapturePicture.Launch(URI)时发送URI。

我的问题是,这是否正确,还如何获得URI,将其保存到内部存储(.openFileOutput()),然后从内部存储中加载它。

我更喜欢Kotlin的答案,但是Java也很好。 关于内部存储中路径如何工作的解释也可能会有所帮助。

I'm new to file storage. My main goal is to take a picture with the camera, store it with good quality, then display it in an ImageView. I want to avoid asking for user permission (to use camera and external storage), and want to make this as simple as possible.

To take a picture, I'm using

val capturePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { it: Boolean -> }.
I don't know how to get the bitmap from this function or if I should. To my understanding I should send the uri when calling capturePicture.launch(uri).

My question is if this is correct, also how do I get the URI, save it to internal storage (.openFileOutput()), then load it from internal storage.

I prefer the answer in Kotlin but Java is fine too.
An explanation on how paths work in internal storage could be helpful too.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深巷少女 2025-02-04 13:31:33

我跟随此中等文章教程,对其进行了调整,并为我的用例添加了更多功能。

在缓存目录中保存的图像

以拍摄图片:

private val takeImageResult =
    registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
        if (isSuccess) {
            latestTmpUri?.let { uri ->
                loadPhotosFromInternalStorageIntoRecyclerView()
            }
        }
    }

要调用图片,保存并获取URI:

private var latestTmpUri: Uri? = null
private fun takeImage() {
    lifecycleScope.launchWhenStarted {
        getTmpFileUri().let { uri ->
            latestTmpUri = uri
            takeImageResult.launch(uri)
        }
    }
}
private fun getTmpFileUri(): Uri {
    val tmpFile = File.createTempFile("tmp_image_file", ".jpg", requireActivity().cacheDir).apply {
        createNewFile()
        deleteOnExit()
    }
    return FileProvider.getUriForFile(requireActivity().applicationContext, "${BuildConfig.APPLICATION_ID}.provider", tmpFile)
}

加载图片(在图片列表中加载第一张图片):

private fun loadPhotosFromInternalStorage(): List<InternalStoragePhoto> {
    val files = requireActivity().cacheDir.listFiles()
    return files?.filter {
        it.canRead() && it.isFile && it.name.endsWith(".jpg")
    }?.map {
        InternalStoragePhoto(it.name, it.toUri())
    } ?: listOf()
}
private fun displayImage() {
    Glide.with(photoImg.context)
        .load(loadPhotosFromInternalStorage()[0].uri)
        .into(photoImg)
}

这是图像的自定义对象:

data class InternalStoragePhoto(
    val name: String,
    val uri: Uri?
)

这是我代码的简化版本,这是测试应用的源代码 github repo

I followed this medium article tutorial, adjusted it and added more functionality for my use case.

Saved images in the cache directory

To take the picture:

private val takeImageResult =
    registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
        if (isSuccess) {
            latestTmpUri?.let { uri ->
                loadPhotosFromInternalStorageIntoRecyclerView()
            }
        }
    }

To call take picture, save it, and get the uri:

private var latestTmpUri: Uri? = null
private fun takeImage() {
    lifecycleScope.launchWhenStarted {
        getTmpFileUri().let { uri ->
            latestTmpUri = uri
            takeImageResult.launch(uri)
        }
    }
}
private fun getTmpFileUri(): Uri {
    val tmpFile = File.createTempFile("tmp_image_file", ".jpg", requireActivity().cacheDir).apply {
        createNewFile()
        deleteOnExit()
    }
    return FileProvider.getUriForFile(requireActivity().applicationContext, "${BuildConfig.APPLICATION_ID}.provider", tmpFile)
}

To load the picture (loads the first picture in the list of pictures):

private fun loadPhotosFromInternalStorage(): List<InternalStoragePhoto> {
    val files = requireActivity().cacheDir.listFiles()
    return files?.filter {
        it.canRead() && it.isFile && it.name.endsWith(".jpg")
    }?.map {
        InternalStoragePhoto(it.name, it.toUri())
    } ?: listOf()
}
private fun displayImage() {
    Glide.with(photoImg.context)
        .load(loadPhotosFromInternalStorage()[0].uri)
        .into(photoImg)
}

Here's the custom object for the images:

data class InternalStoragePhoto(
    val name: String,
    val uri: Uri?
)

This is a simplified version of my code, here's the source code for the test app github repo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文