读取本地相册 兼容了小米
权当记录了;
首先想要调用相册需要执行Intent过去;
private void intentimage() {Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);getAlbum.setType(IMAGE_TYPE);startActivityForResult(getAlbum, IMAGE_CODE);}
private final String IMAGE_TYPE = "image/*";private final int IMAGE_CODE = 1;private final int TAKE_PHOTO = 0;private final int PHOTO_REQUEST_CUT=2;
需要的一些变量;
然后就是在activity的onActivityResult的方法里面得到图片的Url,这里面有个坑,就是小米的手机的不支持这么拿,会报空指针;
public void onActivityResult(int requestCode, int resultCode, Intent data) {ContentResolver resolver = this.getContentResolver();if (data != null) {switch (requestCode) {case TAKE_PHOTO: //拍摄图片并选择// 两种方式 获取拍好的图片Toast.makeText(this, "拍照的", Toast.LENGTH_SHORT).show();if (data.getData() != null || data.getExtras() != null) {//防止没有返回结果Uri uri = data.getData();if (uri == null) {Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT).show();}}break;case IMAGE_CODE:Uri originalUri = data.getData();crop(originalUri);/* Toast.makeText(this, originalUri.getPath(), Toast.LENGTH_SHORT).show();String path1 = MiPictureHelper.getPath(this, originalUri);Bitmap bitmap = PictureUtils.getSmallBitmap(path1, 60, 60);activityCompleteuserPortrait.setImageBitmap(bitmap);saveBitmap(bitmap);*/break;case PHOTO_REQUEST_CUT:// 从剪切图片返回的数据if (data != null) {Bitmap bitmap = data.getParcelableExtra("data");saveBitmap(bitmap);activityCompleteuserPortrait.setImageBitmap(bitmap);}}}super.onActivityResult(requestCode, resultCode, data);}
上面加入了 剪切圆形图片,不需要的可以直接去掉,圆形图片的方法;
/* * 剪切图片 */private void crop(Uri uri) {// 裁剪图片意图Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");intent.putExtra("crop", "true");// 裁剪框的比例,1:1intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// 裁剪后输出图片的尺寸大小intent.putExtra("outputX", 250);intent.putExtra("outputY", 250);intent.putExtra("outputFormat", "JPEG");// 图片格式intent.putExtra("noFaceDetection", true);// 取消人脸识别intent.putExtra("return-data", true);// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUTstartActivityForResult(intent, PHOTO_REQUEST_CUT);}
关键的一个工具类;兼容了小米的地方;
public class MiPictureHelper {@SuppressLint("NewApi")public static String getPath(final Context context, final Uri uri) {final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {// ExternalStorageProviderif (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];}}// DownloadsProviderelse 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);}// MediaProviderelse 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 addressif (isGooglePhotosUri(uri))return uri.getLastPathSegment();return getDataColumn(context, uri, null, null);}// Fileelse if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return null;}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;}public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}private static boolean isGooglePhotosUri(Uri uri) {return "com.google.android.apps.photos.content".equals(uri.getAuthority());}
}
一个图片压缩的工具类;
public class PictureUtils {/*** 计算图片的缩放值** @param options* @param reqWidth* @param reqHeight* @return*/public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {// Raw height and width of imagefinal int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {// Calculate ratios of height and width to requested height and// widthfinal int heightRatio = Math.round((float) height/ (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);// Choose the smallest ratio as inSampleSize value, this will// guarantee// a final image with both dimensions larger than or equal to the// requested height and width.inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}/*** 根据路径获得突破并压缩返回bitmap用于显示** @param filePath* @return*/public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true; //只返回图片的大小信息BitmapFactory.decodeFile(filePath, options);// Calculate inSampleSize//options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);options.inSampleSize = 5;// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds = false;return BitmapFactory.decodeFile(filePath, options);}
}
附上一个读取本地图片并且保存到指定的文件夹的的;
private String portrait;public void saveBitmap(Bitmap bm) {portrait = Environment.getExternalStorageDirectory().getPath() + "/taose/" + System.currentTimeMillis() + ".jpg";File file=new File(Environment.getExternalStorageDirectory().getPath() + "/taose/");file.mkdirs();File f = new File(portrait);Log.i("创建成功了么","chenggl");/* if (f.exists()) {f.delete();}*/try {FileOutputStream out = new FileOutputStream(f);bm.compress(Bitmap.CompressFormat.PNG, 90, out);out.flush();out.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blockLog.i("创建成功了么","chenggl12321");e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blockLog.i("创建成功了么","chenggl6666666666");e.printStackTrace();}}
好了 图片这块就到这了
读取本地相册 兼容了小米相关推荐
- 开启相机,读取本地相册实现
本文主要实现如何打开相机把照的图片展示,还有就是读取本地相册,把选取中的图片返回. 第一步: 权限声明,一个是相机权限一个是读取权限 <uses-permission android:name ...
- c++: 读取访问权限冲突0xcdcdcdcd_微信读取不到本地相册
微信在我们日常生活中经常要使用到,有时候由于设置的不当导致微信无法读取本地相册该如何解决,下面就为大家介绍一下微信读取不到本地相册的解决方法. 微信读取不到本地相册 1.可能是由于您没有打开微信读取本 ...
- Android手机拍照或从本地相册选取图片设置头像。适配小米、华为、7.0
https://www.jianshu.com/p/9404515fde30 传送门 https://github.com/jiaweizeng/BalaPortrait 设置头像通常有两种方式: 1 ...
- android 小米加载大图,Android手机拍照或从本地相册选取图片设置头像。适配小米、华为、7.0...
1,让用户通过选择本地相册之类的图片库中已有的图像,裁剪后作为头像. 2,让用户启动手机的相机拍照,拍完照片后裁剪,然后作为头像. 代码如下 MainActivity.Java文件: package ...
- android 从相册读取多张图片大小,Android优化查询加载大数量的本地相册图片
一.概述 讲解优化查询相册图片之前,我们先来看下PM提出的需求,PM的需求很简单,就是要做一个类似微信的本地相册图片查询控件,主要包含两个两部分: 进入图片选择页面就要显示出手机中所有的照片,包括系统 ...
- Android基于红米系列手机读取本地图片路径失败的解决方案
最近 公司的项目上有 扫描二维码功能,当然必不可少的就会有读取本地二维码需求.首先就是跳转到本地相册,如下代码: /*** show images in the android device medi ...
- android 下载保存视频到本地相册刷新 机型适配问题
android 下载保存视频到本地相册刷新 机型适配问题 android 下载保存视频到本地相册刷新问题 一般我们保存视频文件到本地 使用一下方法扫描到相册,通知相册更新 MediaScannerCo ...
- android读取外部图片,Android读取本地图库与调用摄像头拍摄
本文主要介绍如何读取Android本地图库的图片以及调用安卓的摄像头进行拍摄. 一.布局 布局比较简单,MainActviivty的布局文件只有两个按钮,一个是读取图库的,另一个是打开摄像头的,另外R ...
- iOS 根据图片URL从本地相册获取图片
最近做一个聊天的项目,需要发送图片后读取本地图片显示到列表里.刚开始的时候,天真的认为可以用SDWebImage直接加载,然后并不能行. 于是在网上搜了搜,如何根据从相册获取的UIImagePicke ...
最新文章
- 记录一下PyQt5界面导入Python(绕开pyqt5-tools安装失败问题)
- Linux常用命令--文件(夹)查找之find命令
- HYSBZ - 2160 拉拉队排练(回文自动机)
- 87-区间线段树(板子)--那个苑区的人最瘦
- c语言程序设计对称字符串,C语言程序设计(字符串)
- 一段比较好的加1操作。能够防止简单的++造成的溢出。
- 引入LeakCanary到项目
- abd串口工具使用教程_如何使用命令刷机 ADB与FASTBOOT工具使用教程
- ResourceHacker(4.5.30)单文件绿色汉化版
- 2022年第五届中青杯赛题浅评
- java中的URLEncoder和URLDecoder类
- Linux找回删除文件
- getStyle(getComputedStyle currentstyle) 获取非行间样式函数封装
- 2018 第九届 蓝桥杯 JavaB组 摔手机(动态规划解决)
- java实现随机点名器
- Android图像处理之Paint
- 数据标准化的原因及方法
- Debian中文环境配置及几种中文编码的探究
- 一个C程序是如何运行的
- 清华深圳计算机科学,江勇(清华大学深圳研究生院教授)_百度百科
热门文章
- 【茗创科技】婴儿脑电机器学习实用指南
- HDOJ 4239 - Decoding EDSAC Data 模拟
- CodeForces 698C LRU
- 【数据可视化】python/pyecharts 画地图(热力图)(世界地图,省市地图,区县地图)、动态流向图
- 计算机的存储器(详解)
- python分析数据走势图_python绘制趋势图的示例
- ANDROID内存优化(大汇总——全)
- 安装北洋雷达驱动以及可能遇到的问题
- python统计单词个数算法_python 统计单词个数和频次
- 传统单节点网站的 Serverless 上云