簡體   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