Android 4.4从图库选择图片,获取图片路径并裁剪
转至 http://blog.csdn.net/tempersitu/article/details/20557383
最近在做一个从图库选择图片或拍照,然后裁剪的功能.本来是没问题的,一直在用
- Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
的方式来做,是调用系统图库来做,但是发现如果有图片是同步到google相册的话,图库里面能看到一个auto backup的目录,点进去选图片的话是无法获取到图片的路径的.因为那些图片根本就不存在于手机上.然后看到无论是百度贴吧,Instagram,或者还有些会选取图片做修改的app,都是用一个很漂亮的图片选择器(4.4以上,4.3的还是用系统旧的图库).
而这个图片选择器可以屏蔽掉那个auto backup的目录.所以就开始打算用这个图片选择器来选图片了.
这个方法就是
- Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
- intent.addCategory(Intent.CATEGORY_OPENABLE);
- intent.setType("image/jpeg");
- if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
- startActivityForResult(intent, SELECT_PIC_KITKAT);
- }else{
- startActivityForResult(intent, SELECT_PIC);
- }
为什么要分开不同版本呢?其实在4.3或以下可以直接用ACTION_GET_CONTENT的,在4.4或以上,官方建议用ACTION_OPEN_DOCUMENT,但其实都不算太大区别,区别是他们返回的Uri,那个才叫大区别.这就是困扰了我一整天的问题所在了.
4.3或以下,选了图片之后,根据Uri来做处理,很多帖子都有了,我就不详细说了.主要是4.4,如果使用上面pick的原生方法来选图,返回的uri还是正常的,但如果用ACTION_GET_CONTENT的方法,返回的uri跟4.3是完全不一样的,4.3返回的是带文件路径的,而4.4返回的却是content://com.android.providers.media.documents/document/image:3951这样的,没有路径,只有图片编号的uri.这就导致接下来无法根据图片路径来裁剪的步骤了.
还好找了很多方法,包括加权限啊什么的,中间还试过用一些方法,自己的app没崩溃,倒是让系统图库崩溃了,引发了java.lang.SecurityException.
- Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{437b5d88 9494:com.google.android.gallery3d/u0a20} (pid=9494, uid=10020) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
看来4.4的系统还是有些bug.重点来了,4.4得到的uri,需要以下方法来获取文件的路径
- public static String getPath(final Context context, final Uri uri) {
- final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
- // DocumentProvider
- if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
- // ExternalStorageProvider
- if (isExternalStorageDocument(uri)) {
- final String docId = DocumentsContract.getDocumentId(uri);
- final String[] split = docId.split(":");
- final String type = split[0];
- if ("primary".equalsIgnoreCase(type)) {
- return Environment.getExternalStorageDirectory() + "/" + split[1];
- }
- // TODO handle non-primary volumes
- }
- // DownloadsProvider
- else if (isDownloadsDocument(uri)) {
- final String id = DocumentsContract.getDocumentId(uri);
- final Uri contentUri = ContentUris.withAppendedId(
- Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
- return getDataColumn(context, contentUri, null, null);
- }
- // MediaProvider
- else if (isMediaDocument(uri)) {
- final String docId = DocumentsContract.getDocumentId(uri);
- final String[] split = docId.split(":");
- final 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;
- }
- final String selection = "_id=?";
- final String[] selectionArgs = new String[] {
- split[1]
- };
- return getDataColumn(context, contentUri, selection, selectionArgs);
- }
- }
- // MediaStore (and general)
- else if ("content".equalsIgnoreCase(uri.getScheme())) {
- // Return the remote address
- if (isGooglePhotosUri(uri))
- return uri.getLastPathSegment();
- return getDataColumn(context, uri, null, null);
- }
- // File
- else if ("file".equalsIgnoreCase(uri.getScheme())) {
- return uri.getPath();
- }
- return null;
- }
- /**
- * Get the value of the data column for this Uri. This is useful 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.
- */
- 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;
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is ExternalStorageProvider.
- */
- public static boolean isExternalStorageDocument(Uri uri) {
- return "com.android.externalstorage.documents".equals(uri.getAuthority());
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is DownloadsProvider.
- */
- public static boolean isDownloadsDocument(Uri uri) {
- return "com.android.providers.downloads.documents".equals(uri.getAuthority());
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is MediaProvider.
- */
- public 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 Google Photos.
- */
- public static boolean isGooglePhotosUri(Uri uri) {
- return "com.google.android.apps.photos.content".equals(uri.getAuthority());
- }
这样,就可以在4.4上用漂亮的图片选择器,选到我们想要的文件,又不会出问题了.
昨天发现了个bug,如果在4.4上面不用"图片"来选,用"图库"来选,就会无法读取到图片路径,所以只需要加个判断,如果是用旧方式来选,就用旧方式来读,就是如果
DocumentsContract.isDocumentUri(context, uri) 返回false的话,就用旧的方式
- public static String selectImage(Context context,Intent data){
- Uri selectedImage = data.getData();
- // Log.e(TAG, selectedImage.toString());
- if(selectedImage!=null){
- String uriStr=selectedImage.toString();
- String path=uriStr.substring(10,uriStr.length());
- if(path.startsWith("com.sec.android.gallery3d")){
- Log.e(TAG, "It's auto backup pic path:"+selectedImage.toString());
- return null;
- }
- }
- String[] filePathColumn = { MediaStore.Images.Media.DATA };
- Cursor cursor = context.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- String picturePath = cursor.getString(columnIndex);
- cursor.close();
- return picturePath;
- }
这样就OK的了
Android 4.4从图库选择图片,获取图片路径并裁剪的更多相关文章
- Android 从 Android 本地图库选择多个图片
原文地址 本文说明如何从 Android 本地图库选择多个图片.作者考虑很多解决方案. 演示从 Android 本地图库选择多个图片,有两个方法可以实现从图库中选择多个图片: 用 Intent 获取多 ...
- android 拍照或者图库选择 压缩后 图片 上传
通过拍照或者从相册里选择图片通过压缩并上传时很多应用的常用功能,记录一下实现过程 一:创建个临时文件夹用于保存压缩后需要上传的图片 /** * path:存放图片目录路径 */ private Str ...
- UIImagePickerController从拍照、图库、相册获取图片
iOS 获取图片有三种方法: 1. 直接调用摄像头拍照 2. 从相册中选择 3. 从图库中选择 UIImagePickerController 是系统提供的用来获取图片和视频的接口: 用UIImage ...
- javascript加载图片获取图片尺寸信息方法
如果你遇到不方便从服务器取图片尺寸信息的话,用下面代码就很方便了. // 更新: // 05.27: 1.保证回调执行顺序:error > ready > load:2.回调函数this指 ...
- Android笔记之从图库选择图片
Demo链接:https://pan.baidu.com/s/1T4T2pTEswmbcYYfpN3OwDw,提取码:pzqy 参考链接:[Android Example] Pick Image fr ...
- Android拍照得到全尺寸图片并进行压缩/拍照或者图库选择 压缩后 图片 上传
http://www.jb51.net/article/77223.htm https://www.cnblogs.com/breeze1988/p/4019510.html
- 前端模拟 图片上传---->>通过选取的图片获取其路径<<------
<head> <meta charset="UTF-8"> <title>Title</title> <style> d ...
- Android系统拍照之后回显并且获取文件路径
/*调用拍照返回*/ case PHOTO_REQUEST_GALLERY: if (data != null) { Uri uri = data.getData(); String photopat ...
- android 照相或从相册获取图片并裁剪
照相或从相册获取图片并裁剪 在android应用中很多时候都要获取图片(例如获取用户的头像)就需要从用户手机上获取图片.可以直接照,也可以从用户SD卡上获取图片,但获取到的图片未必能达到要求.所以要对 ...
随机推荐
- linux命令(41):文件和文件夹的颜色
各个颜色的文件分别代表的是:蓝色表示目录:绿色表示可执行文件:红色表示压缩文件:浅蓝色表示链接文件:灰色表示其它文件:红色闪烁表示链接的文件有问题了:黄色是设备文件,包括block, char, fi ...
- 关于linux上cron服务的python封装工具
关于cron:定时任务服务,一般linux自带且已启动.(pgrep cron查看cron服务是否启动了.) 关于plan:一个通过python来定制cron服务的工具.其官网:http://plan ...
- 读取本地已有的.db数据库
public class MyDB extends SQLiteOpenHelper { // 数据库的缺省路径 private static String DB_PATH ; private sta ...
- 第二章 使用接口(Using Interfaces)-书籍翻译
PDF预览 下载地址 http://files.cnblogs.com/DKSoft/CodingInDelphi.pdf 1.1. 解耦(Decoupling) All through this b ...
- Git补充命令行操作操作
Git命令行基本操作这里有我之前整理的git基本操作,常用的操作. 本文以实际功能和实例来说明git GUI的实现原理. 单独更新特定文件 $ git checkout readme.md 删除特定文 ...
- Oracle事务与锁
Oracle事务与锁 2017-12-13 目录 1 数据库事务概括 1.1 事务定义 1.2 事务生命周期 1.3 事物的特性 1.4 死锁2 事务相关语句 2.1 事务相关语句概括 2 ...
- MySQL字段数据全部查出【只保留中文、英文、数字、空格的词表】
select * from xxx_xxx_bak where slot_type_id in ('xxx', 'xxx') ; by @大超超 记录备查
- django模型查询
概述 查询集表示从数据库获取的对象的集合 查询集可以有多个过滤器 过滤器就是一个函数,基于所给的参数限制查询集结果 从SQL角度来说,查询集和select语句等价,过滤器就像where条件 查询集 在 ...
- 修改urllib2源代码,定制User-Agent,一劳永逸
我经常用到urllib2这个库,基本上每次都要添加 User-Agent 为一个模拟浏览器的值. 突然想到,能不能直接修改源代码,添加 User-Agent 的值. google 到 https:// ...
- curl Array to string conversion 错误
0x00 故障 由于GuzzleHttp在iis上使用错误,于是开始替换其为Unirest,没想到发送了一个curl Array to string conversion 错误 0x01 原因 跟踪调 ...