2025年3月29日 星期六 甲辰(龙)年 月廿八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > 安卓(android)开发

android 获取图片的真实地址

时间:02-13来源:作者:点击数:44

在开发中我们需要获取手机上的图片信息, 系统提供的有时候是一个可以访问展示的uri地址,但是当我们需要对图片进行一定的操作时比如 删除。这个时候去删除是无法操作的,因为系统提供的地址并不是对应图片在手机中的真实文件路径。所以需要对uri进行一定的转换。

  • /**
  • * 根据图片的Uri获取图片的绝对路径(已经适配多种API)
  • * @return 如果Uri对应的图片存在,那么返回该图片的绝对路径,否则返回null
  • */
  • public static String getRealPathFromUri(Context context, Uri uri) {
  • int sdkVersion = Build.VERSION.SDK_INT;
  • if (sdkVersion < 11) {
  • // SDK < Api11
  • return getRealPathFromUri_BelowApi11(context, uri);
  • }
  • if (sdkVersion < 19) {
  • // SDK > 11 && SDK < 19
  • return getRealPathFromUri_Api11To18(context, uri);
  • }
  • // SDK > 19
  • return getRealFilePath(context, uri);
  • }
  • /**
  • * 适配api11-api18,根据uri获取图片的绝对路径
  • */
  • private static String getRealPathFromUri_Api11To18(Context context, Uri uri) {
  • String filePath = null;
  • String[] projection = { MediaStore.Images.Media.DATA};
  • CursorLoader loader = new CursorLoader(context, uri, projection, null,
  • null, null);
  • Cursor cursor = loader.loadInBackground();
  • if (cursor != null) {
  • cursor.moveToFirst();
  • filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
  • cursor.close();
  • }
  • return filePath;
  • }
  • /**
  • * 适配api11以下(不包括api11),根据uri获取图片的绝对路径
  • */
  • private static String getRealPathFromUri_BelowApi11(Context context, Uri uri) {
  • String filePath = null;
  • String[] projection = { MediaStore.Images.Media.DATA };
  • Cursor cursor = context.getContentResolver().query(uri, projection,
  • null, null, null);
  • if (cursor != null) {
  • cursor.moveToFirst();
  • filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
  • cursor.close();
  • }
  • return filePath;
  • }
  • /**
  • * @param context
  • * @param uri
  • * @return 文件绝对路径或者null
  • */
  • private static String getRealFilePath( final Context context, final Uri uri ) {
  • if ( null == uri ) return null;
  • final String scheme = uri.getScheme();
  • String data = null;
  • if ( scheme == null )
  • data = uri.getPath();
  • else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
  • data = uri.getPath();
  • } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
  • Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
  • if ( null != cursor ) {
  • if ( cursor.moveToFirst() ) {
  • int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
  • if ( index > -1 ) {
  • data = cursor.getString( index );
  • }
  • }
  • cursor.close();
  • }
  • }
  • return data;
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门