android 获取本地图片资源

三种方式:

1.通过摄像头拍摄获取。

2.通过读取本地image类型文件,可以是png,jpg等,所以是image/*。

3.第三种方式比较麻烦,是通过读取系统存储Provider获取到图片路径后,整理显示到应用内。

通过代码分别介绍实现方式:

1.通过摄像头获取

权限问题:

使用api23以上编译,在6.0系统运行

需要动态获取权限,相关接口在Debug类中。

其他情况在清单文件中配置即可:

<span style="white-space:pre">	</span><uses-permission android:name="android.permission.CAMERA"/>//摄像头权限,SD卡读写权限
<span style="white-space:pre">	</span><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<span style="white-space:pre">	</span><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

相关代码:

<span style="white-space:pre">	</span>//主要是指定好文件的输出目录,通过onActivityResult接口监听回调,从制定的路径查找即可。
<span style="white-space:pre">	</span>Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String imgurl = new File(FileUtils.getTriImgDir(), System.currentTimeMillis() + "").getAbsolutePath();
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imgurl)));
        startActivityForResult(openCameraIntent, requestcode);<span style="font-family: Arial, Helvetica, sans-serif;">	</span>

2.通过读取文件获取

权限问题同以上相同。

相关代码:

<span style="white-space:pre">	</span>//两种方式,一种是4.4以上的通过open_document获取,另一种是4.4以下通过get_content方式获取,区别在于onActivityResult返回值,非常麻烦。
<span style="white-space:pre">	</span>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, requestcode);
        } else {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, requestcode);
        }
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_7_285269" name="code" class="java"><span style="white-space:pre">	</span>//onActivityResult对两种方式返回的处理
<span style="white-space:pre">	</span>Uri uri = data.getData();//通过intent获取到uri这个一样,以下就要区别对待了,非常麻烦,但是基本都是通过uri再去系统媒体库中获取了。
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_10_7044548" name="code" class="java"><span style="white-space:pre">	public static String getPath(Context context, Uri uri) {
     	boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
	     if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                String documentId = DocumentsContract.getDocumentId(uri);
                String[] split = documentId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownLoadsDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                String[] split = id.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }


                String selection = "_id=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if (isKitKat && !DocumentsContract.isDocumentUri(context, uri)) {
            return selectImage(context, uri);
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }</span>
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_12_8973231" name="code" class="java">    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    public static boolean isDownLoadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_14_8950067" name="code" class="java"><span style="white-space:pre">	</span>public static String selectImage(Context context, Uri uri) {
        String picturePath = "";
        if (uri != null) {
            String uriStr = uri.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                picturePath = null;
            }
        } else {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        return picturePath;
    }
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};


        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

3.最后一种其实比较简单,只不过是我们要写的代码多一点,以附件形式上传文件 http://download.csdn.net/detail/lilinwang1990/9633178




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值