我在获取图像路径时遇到问题,当我在 activity 上获取图像时结果数据不为空但无法获取其路径
I have problem in getting image path, when I get image in on activity result data is not empty but unable to get its path
这就是我想要做的。但是记录的路径不正确。当我尝试从记录的路径获取文件时,它说文件不存在。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
if (data?.data != null) {
val imagePath: String? = data.data?.path
if (imagePath != null) {
Log.d("logKey", imagePath)
}
}
}
}
}
试试这个,
在你的项目中添加这个class
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
//import android.provider.<span id="IL_AD11" class="IL_AD">MediaStore</span>;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.KITKAT)
object ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
var nopath = "Select Video Only"
@SuppressLint("NewApi")
fun getPath(context: Context, uri: Uri): String? {
// check here to KITKAT or new version
val isKitKat = true
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":").toTypedArray()
val type = split[0]
if ("primary".equals(type, ignoreCase = true)) {
return (Environment.getExternalStorageDirectory().toString() + "/"
+ split[1])
}
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
java.lang.Long.valueOf(id)
)
return getDataColumn(context, contentUri, null, null)
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":").toTypedArray()
val type = split[0]
var contentUri: Uri? = null
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
return getDataColumn(
context, contentUri, selection,
selectionArgs
)
}
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
// Return the remote address
return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(
context,
uri,
null,
null
)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
return uri.path
}
return nopath
}
/**
* Get the value of the data column for this Uri. This is <span id="IL_AD2" class="IL_AD">useful</span> for MediaStore Uris, and other file-based
* ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
fun getDataColumn(
context: Context, uri: Uri?,
selection: String?, selectionArgs: Array<String>?
): String {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = context.contentResolver.query(
uri!!, projection,
selection, selectionArgs, null
)
if (cursor != null && cursor.moveToFirst()) {
val index = cursor.getColumnIndexOrThrow(column)
return cursor.getString(index)
}
} finally {
cursor?.close()
}
return nopath
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
fun isGooglePhotosUri(uri: Uri): Boolean {
return "com.google.android.apps.photos.content" == uri
.authority
}
}
将此代码添加到您的 onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.data != null) {
val uri = data.data
val realPath = ImageFilePath.getPath(this, data.data!!)
// realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Log.i(TAG, "onActivityResult: file path : $realPath")
try {
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
// Log.d(TAG, String.valueOf(bitmap));
binding.imageView.setImageBitmap(bitmap)
binding.imageView.visibility = View.VISIBLE
} catch (e: IOException) {
e.printStackTrace()
}
} else {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show()
}
}
这就是我想要做的。但是记录的路径不正确。当我尝试从记录的路径获取文件时,它说文件不存在。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
if (data?.data != null) {
val imagePath: String? = data.data?.path
if (imagePath != null) {
Log.d("logKey", imagePath)
}
}
}
}
}
试试这个,
在你的项目中添加这个class
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
//import android.provider.<span id="IL_AD11" class="IL_AD">MediaStore</span>;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.KITKAT)
object ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
var nopath = "Select Video Only"
@SuppressLint("NewApi")
fun getPath(context: Context, uri: Uri): String? {
// check here to KITKAT or new version
val isKitKat = true
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":").toTypedArray()
val type = split[0]
if ("primary".equals(type, ignoreCase = true)) {
return (Environment.getExternalStorageDirectory().toString() + "/"
+ split[1])
}
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
java.lang.Long.valueOf(id)
)
return getDataColumn(context, contentUri, null, null)
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":").toTypedArray()
val type = split[0]
var contentUri: Uri? = null
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
return getDataColumn(
context, contentUri, selection,
selectionArgs
)
}
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
// Return the remote address
return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(
context,
uri,
null,
null
)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
return uri.path
}
return nopath
}
/**
* Get the value of the data column for this Uri. This is <span id="IL_AD2" class="IL_AD">useful</span> for MediaStore Uris, and other file-based
* ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
fun getDataColumn(
context: Context, uri: Uri?,
selection: String?, selectionArgs: Array<String>?
): String {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = context.contentResolver.query(
uri!!, projection,
selection, selectionArgs, null
)
if (cursor != null && cursor.moveToFirst()) {
val index = cursor.getColumnIndexOrThrow(column)
return cursor.getString(index)
}
} finally {
cursor?.close()
}
return nopath
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri
.authority
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
fun isGooglePhotosUri(uri: Uri): Boolean {
return "com.google.android.apps.photos.content" == uri
.authority
}
}
将此代码添加到您的 onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.data != null) {
val uri = data.data
val realPath = ImageFilePath.getPath(this, data.data!!)
// realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Log.i(TAG, "onActivityResult: file path : $realPath")
try {
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
// Log.d(TAG, String.valueOf(bitmap));
binding.imageView.setImageBitmap(bitmap)
binding.imageView.visibility = View.VISIBLE
} catch (e: IOException) {
e.printStackTrace()
}
} else {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show()
}
}