最近由于项目的需要,要求用户可以上传自己拍的照片和图库中的已有照片,这是一个App比较基础性的功能,就索性将整个功能抽出来写成一个组件,以方面其它的App再实现此功能时可直接拿来使用.

 话不多说,先看一下效果图,弹出选择方式window :

点击:Select from gallery,从本地机册中选择图片,如图:

点击:Take a photot就不再上传截图了.

下面将实现的主要代码出,如有需要可稍做修改即可做为一个组件使用,以下没布局文件.

public class TakePhoto
{protected Activity mActivity;protected Intent mIntent = null;protected static final int PHOTO_REQUEST_TAKEPHOTO = 0x00000001;protected static final int PHOTO_REQUEST_CUT = 0x00000002;protected Uri currentUri = null;protected TakePhotoListener mTakePhotoListener;protected View mDisplayView;private String sdcardPath = null;private String fileBasePath = null;private int aspectX = 1;private int aspectY = 1;private int outputX = 480;private int outputY = 480;public TakePhoto(Activity activity, View displayView, TakePhotoListener takePhotoListener){this.mActivity = activity;this.mDisplayView = displayView;this.mTakePhotoListener = takePhotoListener;initLocalFilePath(mActivity);startSelectImage();}public TakePhoto(Activity activity, View displayView, int aspectX, int aspectY, int outputX, int outputY,TakePhotoListener takePhotoListener){this.mActivity = activity;this.mDisplayView = displayView;this.aspectX = aspectX;this.aspectY = aspectY;this.outputX = outputX;this.outputY = outputY;this.mTakePhotoListener = takePhotoListener;initLocalFilePath(mActivity);startSelectImage();}private void initLocalFilePath(Activity activity){sdcardPath = activity.getExternalCacheDir().toString() + "/capturePicture/";fileBasePath = "file://" + sdcardPath;}public void onActivityResult(int requestCode, int resultCode, Intent data){switch (requestCode){case PHOTO_REQUEST_CUT:try{setDisplayViewImage();}catch (FileNotFoundException e){mTakePhotoListener.onFail(TakePhotoFailReason.FileNotFound);}catch (OutOfMemoryError e){mTakePhotoListener.onFail(TakePhotoFailReason.OutOfMemory);}break;}}protected void startSelectImage(){}protected Uri getCurrentUri(){Date date = new Date(System.currentTimeMillis());SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");Log.i("------currentImageUri--------", fileBasePath + dateFormat.format(date) + ".jpg");return Uri.parse(fileBasePath + dateFormat.format(date) + ".jpg");}protected void cropImageUri(Uri uri){try{// ���òü�mIntent.putExtra("crop", "true");// aspectX aspectY �ǿ�ߵı���mIntent.putExtra("aspectX", aspectX);mIntent.putExtra("aspectY", aspectY);// outputX outputY �Dzü�ͼƬ���mIntent.putExtra("outputX", outputX);mIntent.putExtra("outputY", outputY);mIntent.putExtra("scale", true);mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);mIntent.putExtra("return-data", false);mIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());mIntent.putExtra("noFaceDetection", true); // no face detectionmActivity.startActivityForResult(mIntent, PHOTO_REQUEST_CUT);}catch (ActivityNotFoundException e){mTakePhotoListener.onFail(TakePhotoFailReason.ActivityNotFound);}}protected void setDisplayViewImage() throws FileNotFoundException{if (currentUri != null){Bitmap bitmap = BitmapFactory.decodeFile(currentUri.getPath());if (bitmap == null){throw new FileNotFoundException();}if (mDisplayView instanceof ImageView){((ImageView) mDisplayView).setImageBitmap(bitmap);}else{Drawable drawable = new BitmapDrawable(mActivity.getResources(), bitmap);mDisplayView.setBackgroundDrawable(drawable);}mTakePhotoListener.onSuccess(currentUri.getPath(), mDisplayView, bitmap);}}protected boolean existSDCard(){if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){return true;}else return false;}protected void createPhotoDir(){File file = new File(sdcardPath);if (!file.exists()){file.mkdirs();}}public interface TakePhotoListener{public void onSuccess(String imagePath, View displayView, Bitmap bitmap);public void onFail(TakePhotoFailReason failReason);}public enum TakePhotoFailReason{ActivityNotFound, FileNotFound, OutOfMemory, SDCardNotFound}
}
//TakePhoto子类,实现从相机拍照生成图片
package com.focustech.capturepicture;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;public class CameraTakePhoto extends TakePhoto
{/*** 构造方法* @param activity        页面对象* @param displayView   图片显示对象* @param takePhotoListener   图片回调*/public CameraTakePhoto(Activity activity, View displayView, TakePhotoListener takePhotoListener){super(activity, displayView, takePhotoListener);}/*** 构造方法* @param activity 页面对象* @param displayView   图片显示对象* @param aspectX 裁剪宽比例* @param aspectY  裁剪高比例* @param outputX  裁剪宽度* @param outputY   裁剪高度* @param takePhotoListener 图片回调*/public CameraTakePhoto(Activity activity, View displayView, int aspectX, int aspectY, int outputX, int outputY,TakePhotoListener takePhotoListener){super(activity, displayView, aspectX, aspectY, outputX, outputY, takePhotoListener);}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data){if (resultCode != Activity.RESULT_OK){return;}super.onActivityResult(requestCode, resultCode, data);switch (requestCode){case PHOTO_REQUEST_TAKEPHOTO:cropCurrentImage(currentUri);break;}}private void cropCurrentImage(Uri currentUri){mIntent = new Intent("com.android.camera.action.CROP");mIntent.setDataAndType(currentUri, "image/*");cropImageUri(currentUri);}@Overrideprotected void startSelectImage(){try{if (existSDCard()){createPhotoDir();currentUri = getCurrentUri();Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT, currentUri);mActivity.startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);}else{mTakePhotoListener.onFail(TakePhotoFailReason.SDCardNotFound);}}catch (ActivityNotFoundException e){mTakePhotoListener.onFail(TakePhotoFailReason.ActivityNotFound);}}}//TakePhoto子类,实现从本地图册中选择图片
public class GalleryTakePhoto extends TakePhoto
{/*** 构造方法* @param activity        页面对象* @param displayView    图片显示对象* @param takePhotoListener    图片回调*/public GalleryTakePhoto(Activity activity, View displayView, TakePhotoListener takePhotoListener){super(activity, displayView, takePhotoListener);}/*** 构造方法* @param activity    页面对象* @param displayView    图片显示对象* @param aspectX    裁剪宽比例* @param aspectY    裁剪高比例* @param outputX    裁剪宽度* @param outputY    裁剪高度* @param takePhotoListener    图片回调*/public GalleryTakePhoto(Activity activity, View displayView, int aspectX, int aspectY, int outputX, int outputY,TakePhotoListener takePhotoListener){super(activity, displayView, aspectX, aspectY, outputX, outputY, takePhotoListener);}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data){if (resultCode != Activity.RESULT_OK){return;}super.onActivityResult(requestCode, resultCode, data);}@Overrideprotected void startSelectImage(){if (existSDCard()){createPhotoDir();currentUri = getCurrentUri();mIntent = new Intent(Intent.ACTION_GET_CONTENT);mIntent.setType("image/*");cropImageUri(currentUri);}else{mTakePhotoListener.onFail(TakePhotoFailReason.SDCardNotFound);}}
}

测试Activity...

package com.focustech.capturepicture;import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;import com.focustech.capturepicture.TakePhoto.TakePhotoFailReason;
import com.focustech.capturepicture.TakePhoto.TakePhotoListener;public class TestActivity extends Activity implements OnClickListener
{private RelativeLayout img_btn;private Button btn1;private Button btn2;private TakePhoto takePhoto;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}// ��ʼ���ؼ�private void init(){img_btn = (RelativeLayout) findViewById(R.id.img_btn);btn1 = (Button) findViewById(R.id.btn1);btn2 = (Button) findViewById(R.id.btn2);// ΪImageButton��Button��Ӽ����¼�btn1.setOnClickListener(this);btn2.setOnClickListener(this);}// ����¼�@Overridepublic void onClick(View v){switch (v.getId()){case R.id.btn1:// ������õ�Activity,��ʾ�ؼ�����,��ȡͼƬ�ص�takePhoto = new CameraTakePhoto(this, img_btn, listener);break;case R.id.btn2:takePhoto = new GalleryTakePhoto(this, img_btn, listener);break;}}private TakePhotoListener listener = new TakePhotoListener(){@Overridepublic void onSuccess(String imagePath, View displayView, Bitmap bitmap){//���ݴ���Ŀؼ�ID����switch (displayView.getId()){case R.id.img_btn:Log.e("==========onSuccess=============", imagePath);break;}}@Overridepublic void onFail(TakePhotoFailReason failReason){Log.e("=======onFail===========", failReason.toString());}};@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){if (takePhoto != null){takePhoto.onActivityResult(requestCode, resultCode, data);}}@Overridepublic void onConfigurationChanged(Configuration newConfig){super.onConfigurationChanged(newConfig);}
}

思路:其实功能是没有什么复杂的,就是调用系统功能去实现自己想要的功能,主要想表达的一点就是组件化的编程,好处是非常之多的,只要一次编写,以后就可以直接拿来用了,也正是体现了Java封装的强大之处.组件整个工程上传到了我的资源里,有需要的请下载。

android本地图片选择(相册选取,相机拍摄)相关推荐

  1. Android 从 Android 本地图库选择多个图片

    原文地址 本文说明如何从 Android 本地图库选择多个图片.作者考虑很多解决方案. 演示从 Android 本地图库选择多个图片,有两个方法可以实现从图库中选择多个图片: 用 Intent 获取多 ...

  2. android+获取图库图片+4.4,Android 从 Android 本地图库选择多个图片

    本文说明如何从 Android 本地图库选择多个图片.作者考虑很多解决方案. 演示从 Android 本地图库选择多个图片,有两个方法可以实现从图库中选择多个图片: 用 Intent 获取多个图片 自 ...

  3. android编程 自动裁剪图片,Android编程实现调用相册、相机及拍照后直接裁剪的方法...

    本文实例讲述了Android编程实现调用相册.相机及拍照后直接裁剪的方法.分享给大家供大家参考,具体如下: package com.cvte.health.phone; import java.io. ...

  4. Android实现拍照选择相册图片上传图片(多图片上传)功能

    安卓多图片上传代码 直接上代码 1.主程序入口XML文件 <?xml version="1.0" encoding="utf-8"?> <ma ...

  5. Android拍照与选择相册照片后裁剪图片,相册多出副本问题

    最近做的一个需求,简单的实现上传头像,包含拍照以及选择照片. 但客户要求的是,需要裁剪. 正常实现需求后,回报问题说,每次选择相册中的照片并裁剪后,相册都有出现多一张裁剪后的照片. 看了代码,由于An ...

  6. android 小米手机选择相册图片截取照片不进onActivityResult报“保存时发生错误,保存失败”

    小米选择相册时如果不使用系统截屏,直接压缩不会报"保存时发生错误,保存失败"的错误,如果截屏就会报如上错误. 需要把URI地址转为图片地址,再包成file文件转为URI Uri u ...

  7. android点击选择相册,android: 从相册中选择照片

    虽然调用摄像头拍照既方便又快捷,但并不是每一次我们都需要去当场拍一张照片的. 因为每个人的手机相册里应该都会存有许许多多张照片,直接从相册里选取一张现有的照 片会比打开相机拍一张照片更加常用.一个优秀 ...

  8. android微信图片选择框架,Android仿微信图片选择器ImageSelector使用详解

    今天给大家介绍一个仿微信的图片选择器:ImageSelector.ImageSelector支持图片的单选.限数量的多选和不限数量的多选.支持图片预览和图片文件夹的切换.在上一篇文章 <Andr ...

  9. android 九宫格图片选择(微信朋友圈) 图片预览 (底部recycleview 不卡顿)

    最近做一个功能 就是仿照微信选择图片,图片预览,图片删除的功能 主要涉及以下知识点: 1 在图片预览的页面可以来回滑动,当前图片是选中的就背景变蓝.点击底部切换上半部分的选择.上半部分选择切换底部的选 ...

  10. Android 本地图片相册选择

    // PictureSelector 基础 (必须)implementation 'io.github.lucksiege:pictureselector:v3.10.1'//图片压缩implemen ...

最新文章

  1. .NET Core竟然无法在Mac下进行build
  2. Nosql and Mongodb 介绍
  3. 训练不出结果_工业设计师如何训练自己的设计思维? 问答
  4. Android 实现ListView的A-Z字母排序
  5. java i/o 流详解_java I/O流详解
  6. Linux 基本命令不能用的解决方法
  7. python读取文本数据--完善中
  8. mysql 修改字段名 sql,MySQL中使用SQL语句对字段进行重命名
  9. 全球十大管理咨询公司
  10. VINS-MONO概述
  11. 卓一电子 智能防雷定时插座 ZYT21时控开关 定时功能设置说明书
  12. 迷茫的程序员和中国软件业
  13. 一维信号的频域特征分析python
  14. MySQL单表查询总结
  15. 如何合理安排测试团队人员分工的问题?新梦想软件测试
  16. 高新技术企业补贴政策能通过吗?高新企业补贴什么时候发放
  17. 数据分析学习技能树 | 养成数据分析师的品质和思维模式
  18. 实验一:行为型设计模式之Strategy模式
  19. 400多个免费在线编程与计算机科学课程
  20. (三)JNI常用示例

热门文章

  1. Vue中默认main.js
  2. bootstrap-select 插件使用详解
  3. Mysql 数据库中Exists 关键字的使用
  4. 航迹推演(Odometry)_由左右轮速度v_l,v_r推导车辆的线速度v,角速度w,运动半径r
  5. TensorFlow中数据的feed与fetch
  6. 违反学校防疫规定,这所211高校两研究生被通报批评!
  7. C++调用mask rcnn进行实时检测--opencv4.0
  8. android开发之自定义AutoCompleteTextView
  9. webview的javascript与Native code交互
  10. Jquery ThickBox的使用