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

问题描述

你能帮我吗 我不知道这段代码有什么问题 图片无法保存在手机存储中。这是一个详细信息活动,图片来自 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()
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)