val path = ""; //假设这是图片的路径
val imageFile = File(path)
if (!imageFile.exists()) {
return
}else{
val contentUri = getImageContentUri(context, imageFile)
if (contentUri != null) {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(contentUri, "image/*")
context.startActivity(intent)
}else {
Toast.makeText(context, "无法获取图片 Uri", Toast.LENGTH_SHORT).show()
}
}
//通过图片文件获取它的url
fun getImageContentUri(context: Context, imageFile: File) : Uri? {
val filePath = imageFile.absolutePath
val cursor = context.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Media._ID),
MediaStore.Images.Media.DATA + "=? ",
arrayOf(filePath), null)
return if (cursor != null && cursor.moveToFirst()) {
val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
cursor.close()
Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id)
} else {
if (imageFile.exists()) {
val values = ContentValues()
values.put(MediaStore.Images.Media.DATA, filePath)
context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
} else {
null
}
}
}