将图库中的图片导入并保存到内部存储器

Import and save a picture from the gallery to the internal memory

我正在开发一个 android 应用程序,我需要从图库中导入照片以将它们保存在 phone 的内存中。 我不知道该怎么做,你知道吗?

我在网上查了一下,但只遇到了我们想在画廊中存储的情况...

实际上,在我的应用程序中,我有带有名称和图像的对象。对于图像,我将他的名字(在可绘制对象中)保存为一个字符串,我将通过按名称对其进行排序来检索它。 我还希望能够从 phone 图库中检索图像,但我不知道如何将两者混合使用...

谢谢你!

您可以使用 Android 的 ACTION_PICK 意图从用户图库加载图像,请参阅 here,目标目录为 EXTERNAL_CONTENT_URI。这将允许用户使用某些外部应用程序 select 图像,并在 selection 完成后将 URI 提供回您的应用程序。请注意以下代码使用 Kotlin。

在您的 Activity 中的某处,开始 ACTION_PICK 结果:

val intent = Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, 0)

您将获得图像的 URI 作为 OnActivityResult 中的数据,您需要从那里读取文件并将其写入您的应用存储。由于您还要将此文件加载到 ImageView 中,因此我建议 re-using 流。我在下面的块中包括了一种可能的方法,即将流读入 ByteArray,然后将 ByteArray 写入您的 FileOutputStream 你的 ImageView(通过使用 BitmapFactory class)。

见下文:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == RESULT_OK) {
        val resultUri: Uri? = data?.data

        val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(resultUri))
        val newFile = File(context.filesDir.absolutePath, "aGeneratedFileName.${extension}")

        var inputStream: InputStream? = null
        var byteStream: ByteArrayOutputStream? = null
        var fileOutputStream: FileOutputStream? = null
        var bitmap: Bitmap? = null
        try {
            inputStream = contentResolver.openInputStream(resultUri)
            fileOutputStream = FileOutputStream(newFile)

            IOUtils.copy(inputStream, byteStream)
            var bytes = byteStream.toByteArray()

            fileOutputStream.write(bytes)
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, byteStream.size())
            myImageView.setImageBitmap(bitmap)
        } catch (e: Exception) {
            Log.e(TAG, "Failed to copy image", e)

            inputStream?.close()
            fileOutputStream?.close()
            byteStream?.close()

            return
        } finally {
            inputStream?.close()
            fileOutputStream?.close()
            byteStream?.close()
        }
    } else {
        // Probably handle this error case
    }
}

我假设您希望在您的应用程序下次启动时重新加载您导入的图像,为此您可以在 filesDir 中获取文件列表并使用 [=23] 读取它们=].

您的目标似乎是显示一组图像,如果您还没有,我建议您查看 RecyclerView class 来实现它。但是,如果您 运行 遇到麻烦,我建议您再开一个问题。