繁体   English   中英

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

[英]Import and save a picture from the gallery to the internal memory

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

我在互联网上看过,但只遇到我们想在画廊中存放的情况...

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

谢谢你们!

您可以使用Android的ACTION_PICK意图从用户库加载图像,请参见此处 ,以EXTERNAL_CONTENT_URI作为目标目录。 这将允许用户使用某些外部应用程序选择图像,并在做出选择后将URI提供回您的应用程序。 请注意,下面的代码在Kotlin中。

在您的活动的某处,启动ACTION_PICK以获取结果:

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

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

见下文:

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获取文件列表,并使用BitmapFactory.decodeFile读取它们。

似乎您的目标是显示图像阵列,如果您还没有,我建议您研究RecyclerView类以实现该目标。 如果您遇到麻烦,我建议您再提一个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM