我尝试从图库中打开图像并在Imageview中以相同的Activty显示 . 我添加了 WRITE_EXTERNAL_STORAGE , READ_EXTERNAL_STORAGE , INTERNET 等权限 . 当我从图库中选择图像并返回活动时,它会显示此类错误
09-04 15:02:57.161 31642-31642 / com.androidtutorialpoint.qrcodescanner E / BitmapFactory:无法解码流:java.io.FileNotFoundException:file:/ storage / emulated / 0 / Pictures / Screenshots / Screenshot_20180816-160721 . png(没有这样的文件或目录)
在这里我的代码: -
- 打开图库的按钮点击事件: -
btn?.setOnClickListener(object:View.OnClickListener {override fun onClick(arg0:View){
val i = Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(i, RESULT_LOAD_IMAGE)
}
})
- 这用于在Imageview中使用显示图像: -
覆盖有趣onActivityResult(requestCode:Int,resultCode:Int,data:Intent?){super.onActivityResult(requestCode,resultCode,data)
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
val selectedImage = data.data
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(selectedImage!!,
filePathColumn, null, null, null)
cursor!!.moveToFirst()
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
val picturePath = cursor.getString(columnIndex)
cursor.close()
val imageView = findViewById(R.id.imageView) as ImageView
imageView.setImageBitmap(BitmapFactory.decodeFile("file://" + picturePath))
}
}
1 回答
您的
query()
不需要返回可以使用的文件系统路径 .相反,将
Uri
传递给您最喜欢的图像加载库(Glide,Picasso等) . 他们可以将图像加载到ImageView
中,在后台线程上执行所有I / O操作 .