写项目的时候一般都会用到头像选择功能,现在真理一下.

需求: 头像选择需要有两个选项: 1, 从手机拍照获取; 2, 从相册中获取。

效果如下:

Demo地址:https://github.com/KeithLanding/ImagePicker

关键代码:

一. 调起相册

     public void selectImage() {Intent intent = new Intent(Intent.ACTION_PICK);intent.setType("image/*");//判断系统中是否有处理该Intent的Activityif (intent.resolveActivity(getPackageManager()) != null) {startActivityForResult(intent, REQUEST_IMAGE_GET);} else {showToast("未找到图片查看器");}}

二. 调起相机

    private void dispatchTakePictureIntent() {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 判断系统中是否有处理该Intent的Activityif (intent.resolveActivity(getPackageManager()) != null) {// 创建文件来保存拍的照片File photoFile = null;try {photoFile = createImageFile();} catch (IOException ex) {// 异常处理}if (photoFile != null) {intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);}} else {showToast("无法启动相机");}}/*** 创建新文件** @return* @throws IOException*/private File createImageFile() throws IOException {String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());String imageFileName = "JPEG_" + timeStamp + "_";File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);File image = File.createTempFile(imageFileName,  /* 文件名 */".jpg",         /* 后缀 */storageDir      /* 路径 */);mCurrentPhotoPath = image.getAbsolutePath();return image;}

三. 处理返回结果

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {// 回调成功if (resultCode == RESULT_OK) {String filePath = null;//判断是哪一个的回调if (requestCode == REQUEST_IMAGE_GET) {//返回的是content://的样式filePath = getFilePathFromContentUri(data.getData(), this);} else if (requestCode == REQUEST_IMAGE_CAPTURE) {if (mCurrentPhotoPath != null) {filePath = mCurrentPhotoPath;}}if (!TextUtils.isEmpty(filePath)) {// 自定义大小,防止OOMBitmap bitmap = getSmallBitmap(filePath, 200, 200);mAvatar.setImageBitmap(bitmap);}}}/*** @param uri     content:// 样式* @param context* @return real file path*/public static String getFilePathFromContentUri(Uri uri, Context context) {String filePath;String[] filePathColumn = {MediaStore.MediaColumns.DATA};Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);if (cursor == null) return null;cursor.moveToFirst();int columnIndex = cursor.getColumnIndex(filePathColumn[0]);filePath = cursor.getString(columnIndex);cursor.close();return filePath;}/*** 获取小图片,防止OOM** @param filePath* @param reqWidth* @param reqHeight* @return*/public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;try {BitmapFactory.decodeFile(filePath, options);} catch (Exception e) {e.printStackTrace();}options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);options.inJustDecodeBounds = false;return BitmapFactory.decodeFile(filePath, options);}/*** 计算图片缩放比例** @param options* @param reqWidth* @param reqHeight* @return*/public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {final int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {final int heightRatio = Math.round((float) height / (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}

注意事项

  • 读写权限要加上:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  • 调起相册时,Intent用的Action是Intent.ACTION_PICK,而不是 ACTION_GET_CONTENT,使用后者返回uri在android 4.4及以上和以下会有不同,要分开处理。

Android头像选择(手机和相册)相关推荐

  1. Android 头像选择(拍照、相册裁剪),含7.0的坑

    作者:夏至,欢迎转载,但请保留这段申明,谢谢. http://blog.csdn.net/u011418943/article/details/77712662 首先,好规则,看看自己的实现效果: 当 ...

  2. Cocos2d-x 3.x 头像选择,本地相册图片+图片编辑(Android、IOS双平台)

    大连游戏产业不是很发达,最后,选择一个应用程序外包公司.积累的工作和学习过程中的一点业余生活微信体验,我想分享的游戏小朋友的爱. 在应用开发过程中会经常实用户上传头像的功能,在网上找了N多资料发现没有 ...

  3. Android开发 华为手机读取相册闪退问题

    说明:不管是用的第三方控件还是自己写的,在选择图片或者修改头像时需要访问手机相册,不做处理华为手机会出现闪退,这时通过代码动态设置读写SD卡权限即可. 1.代码: private static fin ...

  4. android 头像选择,裁剪全套解决方案,你值得拥有!

    头像选取,裁切,上传等功能基本上是现在每个app必备的功能,实现起来倒是不复杂,确是要花点时间.恰好前几天把这个功能做完了,本着不重复造轮子的原则,提供一整套解决方案,希望给能用到的小伙伴. 首先放头 ...

  5. android h5选择手机图片或者文件示例

    有时候有种需求,是从手机端的h5界面选择图片或者文件,这里需要用到 onShowFileChooser()方法,h5需要使用input 标签,直接上代码: <!DOCTYPE html> ...

  6. Android之打开手机系统相册

    1.需求 打开系统相册,获取图片进行扫描操作 2.代码实现 Intent pickIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Me ...

  7. android设置本地图片,Android设置头像,手机拍照或从本地相册选取图片作为头像...

     [Android设置头像,手机拍照或从本地相册选取图片作为头像] 像微信.QQ.微博等社交类的APP,通常都有设置头像的功能,设置头像通常有两种方式: 1,让用户通过选择本地相册之类的图片库中已 ...

  8. PopupWindow全屏显示以及适配不同手机屏幕之 应用实例 更换头像,拍照,相册选取附带动画效果

    最近找工作,所以闲余时间还是比较充足的,今晚刚好没有睡意,抽取了一个之前项目中自己写过的一个功能.更换头像,可以拍照,可以从相册选取照片,有裁剪功能.其中的一个坑是PopupWindow的显示位置以及 ...

  9. Android 头像替换,解决华为手机取不到图片

    只用涉及到用户模块的App基本上就会用到头像替换的功能,类似的代码也是信手沾来,百度.GitHub以及各大论坛好博客一大把,随便粘过来就可以用了.但是...有坑.在华为荣耀手机上踩坑了,网上看了下问的 ...

最新文章

  1. 来看看如何使用策略模式干掉讨厌的 if else
  2. 【经验】广西集体户口迁回农村原籍超级攻略
  3. 看穿机器学习(W-GAN模型)的黑箱
  4. 使用系统规则测试System.in和System.out
  5. BugkuCTF-Crypto题rsa
  6. 教你写一个弹幕库,确定不了解一下?
  7. 与时俱进的迅捷多功能转换器
  8. bzoj 1260 (区间dp)
  9. iOS 多语言本地化 完美解决方案【自动+手动】
  10. java编程小bug
  11. 使用Epub.js打开本地Epub文件
  12. 虚拟试戴用时尚拉近了粉丝和剧中人的距离
  13. Debian firmware:failed to load i915/kbl_dmc解决
  14. 《电工学》课程教学大纲- -
  15. kettle将文件路径定义为_kettle学习笔记(三)——kettle资源库、运行方式与日志...
  16. smartsvn9破解及license文件
  17. 【MATLAB航空航天工具箱】学习笔记--采用星历评估日行迹
  18. 天气API-----开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供)
  19. 四十七、Vue路由导航卫视之实例解析
  20. C#将PPT文件转换成图片并轮播展示

热门文章

  1. 项目融资的申请条件是什么
  2. CATIA基于管路端到端解决方案
  3. Buffer flip()方法用法
  4. 诗词必考意象盘点 | 菊花
  5. Fabric 架构与设计
  6. 外媒全方位展示PS5包装盒8K/4K120/HDR 公布数据转移方法
  7. 合并excel表格如何批量完成
  8. vue实现文字上下停顿滚动
  9. 114实名认证未通过_taptap怎么实名认证?实名制登记认证方法[多图]
  10. php项目服务器环境部署