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

转载 晓果博客 2019/7/7 22:16:47

这篇文章主要为大家详细介绍了Android打开手机相册获取图片路径,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

权限


动态申请权限

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?

获取相册返回的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?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找为什么上不了bet356_bet356 下载安装_bet356黑钱网。

上一篇:Android实现选择相册图片并显示功能

下一篇:Android studio设计简易计算器

赞(0)

共有 条评论 网友评论

验证码: 看不清楚?
    IT文章导航
    扫一扫关注最新编程为什么上不了bet356_bet356 下载安装_bet356黑钱