Android take photos or select pictures from gallery and crop _android

Source: Internet
Author: User
Tags mkdir

Today see "The first line of code" above about taking photos and from the photo album selected part of the picture, found always out of effect, so search for other information to learn about the relevant knowledge, write a simple demo.

First, photo selection pictures

1, the use of implicit intent to start the camera

Construction of implicit Intent
Intent Intent = new Intent (mediastore.action_image_capture);
Call System camera
Startactivityforresult (intent, 1);

2, processing the camera to return the results of the photo

The user clicked Cancel
if (data = = null) {return
  ;
} else{
  Bundle extras = Data.getextras ();
  if (extras!= null) {
    //Get taken photo
    Bitmap BM = extras.getparcelable ("data");
  }


Ii. Choose Pictures from Gallery

1, the Construction content choice implicit type intent

Intent Intent = new Intent (intent.action_get_content);

2. Set content type as Picture

Intent.settype ("image/*");

3. Start Picture selection

Startactivityforresult (Intent, 2);

4, processing picture selection results

if (data = = null) {return
  ;
} else{
  //The user selects a picture from the gallery and returns the URI URI URI of the selected picture
  ;
  Gets the URI URI of the user's selected picture
  = Data.getdata ();
}

Three, crop the selected picture

The camera gets the bitmap type, so we need to convert it to a file URI for clipping. At the same time we also have to save the photos taken by the camera to the local.

 /**
 * writes bitmap to a file in the SD card and returns the URI written to the file
 * @param BM
 * @param dirpath
 * @return
 /
Private Uri Savebitmap (Bitmap BM, String dirpath) {
  //new folder is used to store the cropped picture
  file Tmpdir = new file ( Environment.getexternalstoragedirectory () + "/" + Dirpath);
  if (!tmpdir.exists ()) {
    tmpdir.mkdir ();
  }

  New File Store cropped picture file
  img = new File (Tmpdir.getabsolutepath () + "/avator.png");
  try {
    //Open file output stream
    fileoutputstream fos = new FileOutputStream (IMG);
    The BITMAP is compressed and then written to the output stream (the parameters are picture format, image quality and output stream)
    bm.compress (Bitmap.CompressFormat.PNG, N, FOS);
    Refresh output stream
    Fos.flush ();
    Turn off the output stream
    fos.close ();
    Returns the Uri of the file type return
    uri.fromfile (IMG);
  } catch (FileNotFoundException e) {
    e.printstacktrace ();
    return null;
  } catch (IOException e) {
    e.printstacktrace ();
    return null;
  }
}

The picture selected from the gallery returns a URI of the content type, which we need to convert to a file type URI to be cropped.

 /**
* Converts the URI of the content type to the URI of the file type
* @param uri
* @return
/private URI Converturi (Uri uri) {
  InputStream is;
  try {
    //uri----> inputstream is
    = Getcontentresolver (). Openinputstream (Uri);
    InputStream----> Bitmap
    Bitmap BM = Bitmapfactory.decodestream (is);
    Close Flow
    is.close ();
    Return Savebitmap (BM, "temp");
  } catch (FileNotFoundException e) {
    e.printstacktrace ();
    return null;
  } catch (IOException e) {
    e.printstacktrace ();
    return null;
  }

}

The following is the setting of the clipping parameters, with an implicit intent method to start the clipping program

 /**
 * Pass the image information through the URI for cropping
 * @param
 uri
/private void Startimagezoom (Uri uri) {
  //build implicit intent to start the clipping program
  Intent Intent = new Intent ("Com.android.camera.action.CROP");
  Sets the data URI and type as Picture type
  Intent.setdataandtype (URI, "image/*");
  Displays the view as a
  Intent.putextra ("crop", true) that can be cropped;
  The ratio of the cut width is 1:1
  intent.putextra ("Aspectx", 1);
  Intent.putextra ("Aspecty", 1);
  Output picture of the width of the
  Intent.putextra ("Outputx",);
  Intent.putextra ("Outputy",);
  The data after cropping is returned via intent
  Intent.putextra ("Return-data", true);
  Startactivityforresult (Intent, Crop_code);
}

The following are the complete layout files and Java files

--------------------------------------------------------------------------------

Activity_main.xml file

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent "
  android:o" rientation= "vertical" >

  <imageview
    android:id= "@+id/show_image" android:layout_width= "Match_"
    Parent "
    android:layout_height=" 300DP "/>
  <button
    android:id=" @+id/choose_camera
    " Android:layout_width= "Match_parent"
    android:layout_height= "wrap_content"
    android:text= "Camera"/>
  <button
    android:id= "@+id/choose_gallery"
    android:layout_width= "Match_parent"
    android: layout_height= "Wrap_content"
    android:text= "album"/>
</LinearLayout>

Mainactivity.java file

public class Mainactivity extends Appcompatactivity implements View.onclicklistener {//For display of selected pictures private ImageView m

  ImageView;
  private static final int camera_code = 1;
  private static final int gallery_code = 2;

  private static final int crop_code = 3;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_main);
  Initview ();
    private void Initview () {Mimageview = (ImageView) Findviewbyid (r.id.show_image);
    Button Choosecamera = (button) Findviewbyid (R.id.choose_camera);
    Choosecamera.setonclicklistener (this);
    Button Choosegallery = (button) Findviewbyid (r.id.choose_gallery);
  Choosegallery.setonclicklistener (this); 
        @Override public void OnClick (view view) {switch (View.getid ()) {case R.id.choose_camera://Photo Selection
        Choosefromcamera ();
      Break
 Case R.id.choose_gallery://Choose Choosefromgallery from Album ();       Break
    Default:break; }/** * Photo selection/private void Choosefromcamera () {//Build implicit Intent Intent Intent = new Intent (mediast Ore.
    Action_image_capture);
  Call System camera Startactivityforresult (intent, Camera_code); /** * from photo album select Picture */private void Choosefromgallery () {//Build a Content selection of Intent Intent Intent = new Intent (inte Nt.
    Action_get_content);
    Sets the selection type to be a picture type Intent.settype ("image/*");
  Open the picture Select Startactivityforresult (Intent, Gallery_code); 
      @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (Requestcode) {
        Case Camera_code://The user clicked Cancel if (data = = null) {return;
          }else{Bundle extras = Data.getextras ();
            if (extras!= null) {//Get taken photo Bitmap BM = extras.getparcelable ("Data");
            Converts bitmap to uri uri uri = savebitmap (BM, temp);
          Start image cropping  Startimagezoom (URI);
      }} break;
        Case gallery_code:if (data = = null) {return;
          }else{//The user selects a picture from the gallery and returns the URI URI URI of the selected picture;
          Gets the URI URI of the user's Selected picture = Data.getdata ();
          The URI returned is a URI of the content type and cannot be replicated, and needs to be converted to a file URI uri = Converturi (URI);
        Startimagezoom (URI);
      } break;
        Case crop_code:if (data = = null) {return;
          }else{Bundle extras = Data.getextras ();
            if (extras!= null) {//Get to the cropped image Bitmap BM = extras.getparcelable ("Data");
          Mimageview.setimagebitmap (BM);
      }} break;
    Default:break; }/** * Converts the URI of the content type to the URI of the file type * @param URI * @return/private URI Converturi (Uri uri) {Inpu
    Tstream is;
      try {//uri----> InputStream is = Getcontentresolver (). Openinputstream (Uri); InputStream----> Bitmap Bitmap BM = Bitmapfactory.decodestream (IS);
      Close flow is.close ();
    Return Savebitmap (BM, "temp");
      catch (FileNotFoundException e) {e.printstacktrace ();
    return null;
      catch (IOException e) {e.printstacktrace ();
    return null; }/** * writes bitmap to a file in the SD card and returns the Uri written to the file * @param BM * @param dirpath * @return/private Uri Save Bitmap (Bitmap BM, String Dirpath) {//new folder to store cropped picture file Tmpdir = new file (environment.getexternalstoragedirecto
    RY () + "/" + Dirpath);
    if (!tmpdir.exists ()) {Tmpdir.mkdir ();
    ///New File Store cropped picture file img = new files (Tmpdir.getabsolutepath () + "/avator.png");
      try {//Open file output stream FileOutputStream fos = new FileOutputStream (IMG);
      The BITMAP is compressed and then written to the output stream (the parameters are picture format, image quality and output stream) bm.compress (Bitmap.CompressFormat.PNG, N, FOS);
      Refresh output stream Fos.flush ();
      Turn off the output stream fos.close (); Returns the Uri return uri.fromfile of the file type(IMG);
      catch (FileNotFoundException e) {e.printstacktrace ();
    return null;
      catch (IOException e) {e.printstacktrace ();
    return null;
    }/** * Pass image information via URI for crop * @param uri/private void Startimagezoom (URI uri) {//Build implicit intent to start the clipping program
    Intent Intent = new Intent ("Com.android.camera.action.CROP");
    Sets the data URI and type as Picture type Intent.setdataandtype (URI, "image/*");
    Displays the view as a Intent.putextra ("crop", true) that can be cropped;
    The ratio of the cut width is 1:1 Intent.putextra ("Aspectx", 1);
    Intent.putextra ("Aspecty", 1);
    Output picture of the width of the Intent.putextra ("Outputx", 150);
    Intent.putextra ("Outputy", 150);
    The data after cropping is returned via intent Intent.putextra ("Return-data", true);
  Startactivityforresult (Intent, Crop_code);

 }
}

Note: Finally you need to add the memory card read and write permission in the Androidmanifest file

Copy Code code as follows:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name= "Android.permission.READ_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.