如何将图像从 imageview 保存到手机存储?

时间:2021-04-04 22:23:19

标签: image bitmap storage android-imageview android-external-storage

你能帮我吗 我不知道这段代码有什么问题 图片无法保存在手机存储中。这是一个详细信息活动,图片来自 RecyclerView 我用 Glide 库加载它

按钮

button_downloadWall.setOnClickListener {
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            if(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                       100)
            }else{
                saveImageToStorage()
            }
        }else{
            saveImageToStorage()
        }
    }

请求权限

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    if (requestCode == 100){
        if (grantResults.isNotEmpty() &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
            saveImageToStorage()
        }else{
            Toast.makeText(this,"Permission not granted, so image can't be saved in storage",
                    Toast.LENGTH_SHORT).show()
        }
    }
}

将图像保存到存储功能

private fun saveImageToStorage(){
    val externalStorageState = Environment.getExternalStorageState()
    if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
        val storageDirectory = Environment.getExternalStorageDirectory()
        val dir : File = File(storageDirectory.absolutePath + "/DCIM")
        val file = File(storageDirectory,"${System.currentTimeMillis()}.jpg")
        try {
            val stream : OutputStream = FileOutputStream(file)
            var drawable : BitmapDrawable = details_image.drawable as BitmapDrawable
            var bitmap = drawable.bitmap
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
            stream.flush()
            stream.close()
            Toast.makeText(this,"Image saved successfully ${Uri.parse(file.absolutePath )}", Toast.LENGTH_SHORT).show()

        }catch (e : Exception){
            e.printStackTrace()
        }
    }else{
        Toast.makeText(this,"Unable to access the storage", Toast.LENGTH_SHORT).show()
    }
}

0 个答案:

没有答案
相关问题