当前位置: 移动技术网 > 移动技术>移动开发>Android > Android实现相机拍摄、选择、图片裁剪功能

Android实现相机拍摄、选择、图片裁剪功能

2019年07月24日  | 移动技术网移动技术  | 我要评论

最近的一些学习心得:

功能实现:点击圆形头像之后可以实现相册上传或者开启相机,然后把得到的图片经过剪裁,把剪裁过的图片设置为头像的背景图

步骤:第一步:自定义一个类,继承imageview,重写draw方法,实现外观为圆形

第二步:在xml文件中引用该控件

第三步:实现圆形头像的点击事件,点击后显示对话框界面,询问你是打开相册还是相机(自动省略显示对话框的代码)

第四步:根据用户选择情况,打开相册或者相机

第五步:将拍摄的图片或者相册选中的图片进行剪裁,将结果保存在指定内存区域

第六步:更新头像图片

具体实现:

第一步:自定义一个类,继承imageview,重写draw方法,实现外观为圆形

//圆形头像类
public class myroundphoto extends imageview{

 private paint p;
 private bitmap bitmap;
 private context context;
 private int wandheight[]=new int[2];
 private file file;
 
 public myroundphoto(context context, attributeset attrs, int defstyle) {
 super(context, attrs, defstyle);
 // todo auto-generated constructor stub
 
 //获得控件长宽(px)
 wandheight = getwidthandheight(context,attrs);
 
 this.context = context;
 
    //初始化控件
    init();
 
 

 }

 public myroundphoto(context context) {
 super(context);
 // todo auto-generated constructor stub

    //获得控件长宽(px)
 wandheight=getwidthandheight(context,attrs);
 
 this.context = context;
 init();
 }

 public myroundphoto(context context, attributeset attrs) {
 super(context, attrs);
 
 //获得控件长宽(px)
 wandheight=getwidthandheight(context,attrs);
 
 // todo auto-generated constructor stub
 this.context = context;
 init();
 }
 
 @override
 protected void ondraw(canvas canvas) {
 // todo auto-generated method stub
 super.ondraw(canvas);
 canvas.drawbitmap(bitmap, new matrix(), p);
 
 }
 
 private void init(){
 //从手机存储区域获取图片文件(该位置为手机相册选中的图片经过剪裁后的图片的存储路径)
 file = new file(environment.getexternalstoragedirectory(),info.photo_name);
 
    //如果图片文件存在,则显示,否则则创建并显示
 if(file.exists()){
  log.v("文件存在", "是");
  this.bitmap = bitmapfactory.decodefile(file.getabsolutepath());
 }
 else{
  log.v("文件不存在", "是");
  
  //生成默认图片的文件
  this.bitmap=bitmapfactory.decodestream(context.getresources().openrawresource(r.drawable.defalut));
  //person.setpicture()
  fileoutputstream fos=null;
  try {
  fos = new fileoutputstream(file);
  } catch (filenotfoundexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
  }
  bitmap.compress(bitmap.compressformat.png, 100, fos); //压缩
  try {
  fos.flush();
  fos.close();
  } catch (ioexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
  }
  
 }
 
 //将方形的位图转换为圆形的位图
 this.bitmap = toroundbitmap(this.bitmap);
 p = new paint();
  
 }
 
 private bitmap toroundbitmap(bitmap map){
 
 
 //int height = map.getheight()+100;
 int height=convertdip2px(context,this.wandheight[1]); //位图的高度(px)
 int width = convertdip2px(context,this.wandheight[0]);//位图的宽度(px)
 
 //创建画布
 bitmap bit = bitmap.createbitmap(width, height, config.argb_8888);
 canvas canvas = new canvas(bit);
 
 //画笔
 paint paint = new paint();
 paint.setantialias(false);
 int r = (width>height)?height:width;
 
 
 
 //绘制圆形
 rectf rectf = new rectf(0,0,r,r);
 canvas.drawroundrect(rectf, r/2, r/2, paint);
 
 //画头像
 //canvas.drawargb(0, 0, 0, 0);
 paint.setxfermode(new porterduffxfermode(mode.src_in));
 canvas.drawbitmap(map, null,rectf, paint);
 
 //返回圆形位图
 return bit;
 }
 
  //使当前视图无效,从而使系统重新绘制视图
 public void myvalidate(){
 bitmap = bitmapfactory.decodefile(file.getabsolutepath());
 bitmap=toroundbitmap(bitmap);
 invalidate();
 
 }
 
  //将dp转换为px
 private static int convertdip2px(context context, int dip) { 
   float scale = context.getresources().getdisplaymetrics().density; 
   return (int)(dip*scale + 0.5f*(dip>=0?1:-1)); 
 } 
 
 //根据xml文件中的属性,返回宽高(px)
  private static int[] getwidthandheight(context context,attributeset attrs){
 int height,width;
 int n = attrs.getattributecount();
 int wandh[] = new int[2];
 
 
 for(int i=0;i<n;i++){
  string str = attrs.getattributename(i);
  
  //获取宽度
  if(str.equals("layout_width")){  
  //system.out.println(attrs.getattributename(0));
  string sttr = attrs.getattributevalue(i);
  string temp = "";
  int j=0;
  while(sttr.charat(j)>='0'&&sttr.charat(j)<='9'){
   temp+=sttr.charat(j);
   j++;
  }
  wandh[0]=integer.parseint(temp);
  temp="";
  continue;
  }
  
  //获取长度
  if(str.equals("layout_height")){
  //system.out.println(attrs.getattributename(1));
  string sttr = attrs.getattributevalue(i);
  string temp = "";
  int j=0;
  while(sttr.charat(j)>='0'&&sttr.charat(j)<='9'){
   temp+=sttr.charat(j);
   j++;
  }
  //system.out.println("temp"+temp);
  wandh[1]=integer.parseint(temp);
  temp="";
  continue;
  }
 }
 return wandh;
 } 
}

第二步:在xml文件中引用该控件

 <com.包名.myroundphoto
      android:id="@+id/myroundphoto"
        android:layout_width="100dp"
        android:layout_height="100dp" >
        
      </com.包名.myroundphoto>

第三步:实现圆形头像的点击事件,点击后显示对话框界面,询问你是打开相册还是相机(自动省略显示对话框的代码)

public void onclick(view v) {
 // todo auto-generated method stub
 
 //点击头像
 if(v.getid()==r.id.myroundphoto){
  //打开dialogactivity,询问打开照相机还是相册
  intent intent = new intent(guideactivity.this,dialogactivity.class);
  startactivityforresult(intent, info.pick_photo);
 }
 }

 第四步:根据用户选择情况,打开相册或者相机

 image =new file(environment.getexternalstoragedirectory(),info.photo_name);

  public void onclick(view v) {
 // todo auto-generated method stub
 switch(v.getid()){
 
 //打开相机
 case r.id.imagebutton1:{
  intent intent = new intent("android.media.action.image_capture");
  intent.putextra(mediastore.extra_output, uri.fromfile(image));
  startactivityforresult(intent, info.open_camera); 
  break;
 }
 
 //打开相册
 case r.id.imagebutton2:{
  intent intent = new intent(intent.action_pick);
  intent.putextra(mediastore.extra_output, uri.fromfile(image));
  intent.settype("image/*");
  startactivityforresult(intent, info.open_gallery);
  break;
 }
 }
 }

第五步:将拍摄的图片或者相册选中的图片进行剪裁,将结果保存在指定内存区域

protected void onactivityresult(int requestcode, int resultcode, intent data) {
 // todo auto-generated method stub
 super.onactivityresult(requestcode, resultcode, data);
 
 switch(requestcode){
 //打开相机 
 case info.open_camera:{
  if(resultcode==result_ok){
  
  //启动裁剪activity
  log.v("启动剪裁程序", "是的");
  intent intent1 = new intent("com.android.camera.action.crop");
       intent1.setdataandtype(uri.fromfile(image), "image/*");
       intent1.putextra("crop", "true");
       intent1.putextra(mediastore.extra_output, uri.fromfile(image));//
       intent1.putextra("aspectx", 1);
       intent1.putextra("aspecty", 1);
       intent1.putextra("outputformat", bitmap.compressformat.jpeg);
       intent1.putextra("outputx", 720);
       intent1.putextra("outputy", 720);
       intent1.putextra("return-data", false);
       startactivityforresult(intent1, info.crop_photo);
  }
  break;
 }
 
 //打开相册
 case info.open_gallery:{
  
  if(resultcode==result_ok){ 
  //启动剪裁程序
  log.v("启动剪裁程序", "是的");
  intent intent1 = new intent("com.android.camera.action.crop");
       intent1.setdataandtype(uri.fromfile(image), "image/*");
       intent1.putextra("crop", "true");
       intent1.putextra(mediastore.extra_output, uri.fromfile(image));//
       intent1.putextra("aspectx", 1);
       intent1.putextra("aspecty", 1);
       intent1.putextra("outputformat", bitmap.compressformat.jpeg);
       intent1.putextra("outputx", 720);
       intent1.putextra("outputy", 720);
       intent1.putextra("return-data", false);
       startactivityforresult(intent1, info.crop_photo);
  } 
  break;
 }
 
 //裁剪图片
 case info.crop_photo:{
  intent intent=new intent();
  setresult(this.result_ok, intent);
  finish();
  break;
 }
 }
 }

第六步:更新头像图片

   protected void onactivityresult(int requestcode, int resultcode, intent data) {
 // todo auto-generated method stub
 super.onactivityresult(requestcode, resultcode, data);
 
 switch(requestcode){
 //选择头像
 case info.pick_photo:{
  //如果摄取图片成功
  if(resultcode==result_ok){
  log.v("requstcodeguideone", "pick_photo");
  btn_choosephoto.myvalidate(); //使原有视图无效,从而使系统重新绘制视图
  }
  break;
 }
 
 default:{
  break;
 }
 }
 }

注意:需要添加的权限

<uses-permission 
    android:name="android.permission.read_external_storage" 
    /> 
<uses-permission 
  android:name="android.permission.write_external_storage"/>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网