Android to achieve camera shooting, selection, image cutting function _android

Source: Internet
Author: User
Tags stub

Some recent learning experience:

function Realization: Click on the round avatar can upload or open the camera, and then the resulting picture after cutting, the cut of the picture set as the head of the background image

Step: Step One: Customize a class, inherit ImageView, rewrite the draw method, and achieve a rounded appearance

Step Two: Reference the control in an XML file

The third step: the realization of the circular head of the click event, click on the Display dialog box interface, ask you to open the album or camera (automatically omit the Display dialog box code)

Fourth step: According to user choice, open album or camera

Step Fifth: Trim the selected pictures or photo albums and save the results in the specified memory area

Sixth step: Update Avatar Picture

Specific implementation:

Step One: customize a class, inherit ImageView, rewrite the draw method, and achieve a rounded appearance

Circular Avatar class public class Myroundphoto extends imageview{private Paint p;
 Private Bitmap Bitmap;
 private context;
 private int wandheight[]=new int[2];
 
 private file file;
 Public Myroundphoto (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);
 
 TODO auto-generated constructor stub//Get Control long width (px) wandheight = Getwidthandheight (context,attrs);
 
    This.context = context;
 
 

 Initializes the control init ();
 Public Myroundphoto {Super (context);
 
 TODO auto-generated constructor stub//Get Control long width (px) wandheight=getwidthandheight (context,attrs);
 This.context = context;
 Init ();
 
 Public Myroundphoto (context, AttributeSet attrs) {Super (context, attrs);
 
 Get Control long width (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 () {//Get a picture file from the cell phone store (this location is the stored path to the cropped picture of the picture selected for the phone album) file = new file (environment.getexternalstoragedire
 
    Ctory (), info.photo_name);
  If the picture file exists, it is displayed, otherwise the IF (file.exists ()) {log.v ("file exists", "yes") is created and displayed;
 This.bitmap = Bitmapfactory.decodefile (File.getabsolutepath ());
  
  } else{log.v ("file does not exist", "yes");
  The file that generates the default picture 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, FOS);
  Compress try {fos.flush ();
  Fos.close ();
  catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 }//Convert a square bitmap to a circular bitmap 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]); Bitmap height (px) int width = convertdip2px (context,this.wandheight[0]);//Bitmap width (px)//create canvas Bitmap bit = Bitmap.createbitmap
 (width, height, config.argb_8888);
 
 Canvas Canvas = new Canvas (bit);
 Brush Paint Paint = new Paint ();
 Paint.setantialias (FALSE);
 
 
 
 int r = (width>height)? Height:width;
 Draw round RECTF RECTF = new RECTF (0,0,r,r);
 
 Canvas.drawroundrect (RECTF, R/2, R/2, paint);
 Picture Portrait//canvas.drawargb (0, 0, 0, 0);
 Paint.setxfermode (New Porterduffxfermode (mode.src_in));
 
 Canvas.drawbitmap (map, NULL,RECTF, paint);
 Returns a circular bitmap return bit;
 //Invalidates the current view, causing the system to repaint the view public void Myvalidate () {bitmap = Bitmapfactory.decodefile (File.getabsolutepath ());
 Bitmap=toroundbitmap (bitmap);
 
 Invalidate (); ///convert DP to PX private static int convertdip2px (context context, int dip) {Float scale = context.getresources (). GE 
   Tdisplaymetrics (). density; return (int) (diP*scale + 0.5f* (dip>=0?1:-1)); Returns the wide-high (px) private static int[] Getwidthandheight (context Context,attributeset attrs) {int Height,wid according to the attributes in the XML file
 Th
 int n = attrs.getattributecount ();
 
 
 int wandh[] = new INT[2];
  
  for (int i=0;i<n;i++) {String str = attrs.getattributename (i);
  Gets the width 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
  //Get length 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;
 } 
}

Step Two: reference the control in an XML file

 <com. Package name. Myroundphoto
      android:id= "@+id/myroundphoto"
        android:layout_width= "100DP"
        android:layout _height= "100DP" >
        
      </com. Package name .myroundphoto>

The third step: The realization of the circular head of the click event, click on the Display dialog box interface, ask you to open the album or camera (automatically omit the Display dialog box code)

public void OnClick (View v) {
 //TODO auto-generated Method Stub
 
 //Click Avatar
 if (V.getid () ==r.id.myroundphoto) {
  //open dialogactivity, ask to open the camera or album
  Intent Intent = new Intent (guideactivity.this,dialogactivity.class);
  Startactivityforresult (Intent, Info.pick_photo);
 }
 

Fourth Step: According to user choice, open album or camera

 Image =new File (Environment.getexternalstoragedirectory (), info.photo_name);

  public void OnClick (View v) {
 //TODO auto-generated Method stub
 switch (V.getid ()) {
 
 //Open camera
 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;
 
 Open album 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;
 }}}
 

Step Fifth: trim the selected pictures or photo albums and save the results in the specified memory area

protected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Supe
 
 R.onactivityresult (Requestcode, ResultCode, data); Switch (Requestcode) {//Open camera case info.open_camera:{if (RESULTCODE==RESULT_OK) {//Start cropping activity log.v ("Start clipping program",
  "Yes");
       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; //Open album Case info.open_gallery:{if (RESULTCODE==RESULT_OK) {//Boot trim program LOG.V ("Start clipping program", "Yes");
  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;
  }//Crop picture case info.crop_photo:{Intent intent=new Intent (); Setresult (this.
  RESULT_OK, intent);
  Finish ();
 Break
 }
 }
 }

Sixth step: Update avatar Picture

   protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
 //TODO auto-generated method stub
   
    super.onactivityresult (Requestcode, ResultCode, data);
 
 Switch (requestcode) {
 //select Avatar
 case info.pick_photo:{
  //If the picture succeeds if
  (RESULTCODE==RESULT_OK) {
  LOG.V ("Requstcodeguideone", "Pick_photo");
  Btn_choosephoto.myvalidate (); Invalidates the existing view, causing the system to redraw the view
  } break
  ;
 
 default:{break;}}}
 

   

Note: the permissions that need to be added

<uses-permission 
    android:name= "Android.permission.READ_EXTERNAL_STORAGE" 
    /> 
< Uses-permission 
  android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.