欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android打开手机相册获取图片路径

程序员文章站 2022-06-21 09:56:36
本文实例为大家分享了android打开手机相册获取图片路径的具体代码,供大家参考,具体内容如下 根据打开相机返回的uri uri = data.getdata();获...

本文实例为大家分享了android打开手机相册获取图片路径的具体代码,供大家参考,具体内容如下

根据打开相机返回的uri uri = data.getdata();获取该相片的真正sd卡路径!

权限

<uses-permission android:name="android.permission.read_external_storage" />
<uses-permission android:name="android.permission.write_external_storage" />

动态申请权限

string[] mpermissionlist = new string[]{
   manifest.permission.write_external_storage,
   manifest.permission.read_external_storage};
 public static final int request_pick_image = 11101;

打开手机相册

activitycompat.requestpermissions(mainactivity.this, mpermissionlist, 100);
@override
 public void onrequestpermissionsresult(int requestcode, @nonnull string[] permissions, @nonnull int[] grantresults) {
  super.onrequestpermissionsresult(requestcode, permissions, grantresults);
  switch (requestcode) {
   case 100:
    boolean writeexternalstorage = grantresults[0] == packagemanager.permission_granted;
    boolean readexternalstorage = grantresults[1] == packagemanager.permission_granted;
    if (grantresults.length > 0 && writeexternalstorage && readexternalstorage) {
     getimage();
    } else {
     toast.maketext(this, "请设置必要权限", toast.length_short).show();
    }

    break;
  }
 }

 private void getimage() {
  if (build.version.sdk_int < build.version_codes.kitkat) {
   startactivityforresult(new intent(intent.action_get_content).settype("image/*"),
     request_pick_image);
  } else {
   intent intent = new intent(intent.action_open_document);
   intent.addcategory(intent.category_openable);
   intent.settype("image/*");
   startactivityforresult(intent, request_pick_image);
  }
 }

获取相册返回的uri

@override
 protected void onactivityresult(int requestcode, int resultcode, intent data) {
  super.onactivityresult(requestcode, resultcode, data);
  if (resultcode == activity.result_ok) {
   switch (requestcode) {
    case request_pick_image:
     if (data != null) {
      string realpathfromuri = realpathfromuriutils.getrealpathfromuri(this, data.getdata());
     } else {
      toast.maketext(this, "图片损坏,请重新选择", toast.length_short).show();
     }

     break;
   }
  }
 }

这里的data.getdata()返回的就是uri,realpathfromuri 为真正路径

获取真正路径

package com.example.richeditortest;

import android.annotation.suppresslint;
import android.content.contenturis;
import android.content.context;
import android.database.cursor;
import android.net.uri;
import android.os.build;
import android.provider.documentscontract;
import android.provider.mediastore;

public class realpathfromuriutils {
 /**
  * 根据uri获取图片的绝对路径
  *
  * @param context 上下文对象
  * @param uri  图片的uri
  * @return 如果uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
  */
 public static string getrealpathfromuri(context context, uri uri) {
  int sdkversion = build.version.sdk_int;
  if (sdkversion >= 19) { // api >= 19
   return getrealpathfromuriaboveapi19(context, uri);
  } else { // api < 19
   return getrealpathfromuribelowapi19(context, uri);
  }
 }

 /**
  * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
  *
  * @param context 上下文对象
  * @param uri  图片的uri
  * @return 如果uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
  */
 private static string getrealpathfromuribelowapi19(context context, uri uri) {
  return getdatacolumn(context, uri, null, null);
 }

 /**
  * 适配api19及以上,根据uri获取图片的绝对路径
  *
  * @param context 上下文对象
  * @param uri  图片的uri
  * @return 如果uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
  */
 @suppresslint("newapi")
 private static string getrealpathfromuriaboveapi19(context context, uri uri) {
  string filepath = null;
  if (documentscontract.isdocumenturi(context, uri)) {
   // 如果是document类型的 uri, 则通过document id来进行处理
   string documentid = documentscontract.getdocumentid(uri);
   if (ismediadocument(uri)) { // mediaprovider
    // 使用':'分割
    string id = documentid.split(":")[1];

    string selection = mediastore.images.media._id + "=?";
    string[] selectionargs = {id};
    filepath = getdatacolumn(context, mediastore.images.media.external_content_uri, selection, selectionargs);
   } else if (isdownloadsdocument(uri)) { // downloadsprovider
    uri contenturi = contenturis.withappendedid(uri.parse("content://downloads/public_downloads"), long.valueof(documentid));
    filepath = getdatacolumn(context, contenturi, null, null);
   }
  } else if ("content".equalsignorecase(uri.getscheme())) {
   // 如果是 content 类型的 uri
   filepath = getdatacolumn(context, uri, null, null);
  } else if ("file".equals(uri.getscheme())) {
   // 如果是 file 类型的 uri,直接获取图片对应的路径
   filepath = uri.getpath();
  }
  return filepath;
 }

 /**
  * 获取数据库表中的 _data 列,即返回uri对应的文件路径
  *
  * @return
  */
 private static string getdatacolumn(context context, uri uri, string selection, string[] selectionargs) {
  string path = null;

  string[] projection = new string[]{mediastore.images.media.data};
  cursor cursor = null;
  try {
   cursor = context.getcontentresolver().query(uri, projection, selection, selectionargs, null);
   if (cursor != null && cursor.movetofirst()) {
    int columnindex = cursor.getcolumnindexorthrow(projection[0]);
    path = cursor.getstring(columnindex);
   }
  } catch (exception e) {
   if (cursor != null) {
    cursor.close();
   }
  }
  return path;
 }

 /**
  * @param uri the uri to check
  * @return whether the uri authority is mediaprovider
  */
 private static boolean ismediadocument(uri uri) {
  return "com.android.providers.media.documents".equals(uri.getauthority());
 }

 /**
  * @param uri the uri to check
  * @return whether the uri authority is downloadsprovider
  */
 private static boolean isdownloadsdocument(uri uri) {
  return "com.android.providers.downloads.documents".equals(uri.getauthority());
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。