我按照此指令编写了一个程序,以创建Uri图片文件
https://developer.android.com/training/camera/photobasics
我用它来创建文件uri
var photoURI:Uri?=null
val REQUEST_TAKE_PHOTO = 1
private fun dispatchTakePictureIntent() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(packageManager) != null) {
var photoFile: File? = null
try {
photoFile = createImageFile()
} catch (ex: IOException) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"xxx.fileprovider",
photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
}
}
}
然后使用它将Uri发送到另一个活动
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(resultCode != RESULT_CANCELED){
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
var i=Intent(this, NewItemActivity::class.java)
i.putExtra("img", photoURI)
startActivity(i)
}
}
}
在其他活动中,我使用get uri并将其设置为ImageView,但是屏幕上没有图片显示,我检查了保存在手机中的图片
val img = intent.extras.get("img") as Uri
iv = findViewById(R.id.img)
iv?.setImageURI(img)
我也发现这种方法可以从uri设置图像,但仍然无法正常工作
如何将内容文件uri设置为ImageView?
var p = getPath(img)
var b = lessenUriImage(p)
iv?.setImageBitmap(b)
fun getPath(uri: Uri): String {
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = managedQuery(uri, projection, null, null, null)
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
fun lessenUriImage(path: String): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
var bitmap = BitmapFactory.decodeFile(path, options)
options.inJustDecodeBounds = false
var be = (options.outHeight / 320.toFloat()).toInt()
if (be <= 0)
be = 1
options.inSampleSize = be
bitmap = BitmapFactory.decodeFile(path, options)
val w = bitmap.width
val h = bitmap.height
println(w.toString() + " " + h)
return bitmap
}