Android perfect for taking photos choose picture clipping and other code sharing _android

Source: Internet
Author: User

In the preface, the issue of version compatibility is mainly due to the errors caused by the different formats of URIs prior to 4.4 and 4.4.

1. Take photos and choose pictures
① Select pictures

 Intent = new Intent (intent.action_get_content);
       Intent.settype ("image/*");
       Startactivityforresult (Intent, Gallery_request_code);

② Photos

 Intent = new Intent (mediastore.action_image_capture);
       Startactivityforresult (Intent, Camera_request_code);

2. Get the value from the system

Tag character

 private static int camera_request_code = 1;
 private static int gallery_request_code = 2;



 private static int crop_request_code = 3; @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Camera_re
     Quest_code) {if (data = null) {return;
       else {//photo Bundle extras = Data.getextras ();
         if (extras!= null) {Bitmap BM = extras.getparcelable ("Data");
         Uri uri = Savebitmap (BM);
       Startimagezoom (URI);
     }} else if (Requestcode = = Gallery_request_code) {if (data = null) {//album return;
     } URI Uri;
     URI = Data.getdata ();
     Uri Fileuri = Converturi (URI);
   Startimagezoom (Fileuri);
     else if (Requestcode = = Crop_request_code) {if (data = = null) {return;
     }//trimmed picture Bundle extras = Data.getextras ();
     if (extras = = null) {return;
     Bitmap BM = extras.getparcelable ("Data"); ShowimagEview (BM);

 }
 }

3. After the picture selection, according to the URL into a stream and save

Private Uri Converturi (Uri uri) {
    InputStream is = null;
    try {is
      = Getcontentresolver (). Openinputstream (URI);
      Bitmap Bitmap = Bitmapfactory.decodestream (is);
      Is.close ();
      Return Savebitmap (bitmap);
    } catch (FileNotFoundException e) {
      e.printstacktrace ();
      return null;
    } catch (IOException e) {
      e.printstacktrace ();
      return null;
    }
  }

4. Save the picture remember to add permission

Private Uri Savebitmap (Bitmap BM) {
    file Tmpdir = new File (environment.getexternalstoragedirectory ()
        + "/ Xiaoxin ");
    if (!tmpdir.exists ()) {
      tmpdir.mkdir ();
    }
    File img = new file (Tmpdir.getabsolutepath () + "love.png");
    try {
      FileOutputStream fos = new FileOutputStream (IMG);
      Bm.compress (Bitmap.CompressFormat.PNG, N, FOS);
      Fos.flush ();
      Fos.close ();
      Toast.maketext (Mainactivity.this, "successful", Toast.length_short). Show ();
      Return Uri.fromfile (IMG);
    } catch (FileNotFoundException e) {
      toast.maketext (mainactivity.this, "failed", Toast.length_short). Show ();
      E.printstacktrace ();
      return null;
    } catch (IOException e) {
      e.printstacktrace ();
      Toast.maketext (Mainactivity.this, "failed", Toast.length_short). Show ();
      return null;
    }

  }

5. Trim picture

/**
   * Trim Picture
   * 
   * @param uri
   /
  private void Startimagezoom (Uri uri) {
    Intent Intent = new Intent ("C Om.android.camera.action.CROP ");
    Intent.setdataandtype (URI, "image/*");
    Intent.putextra ("Crop", "true");
    Intent.putextra ("Aspectx", 1);
    Intent.putextra ("Aspecty", 1);
    Intent.putextra ("Outputx",);
    Intent.putextra ("Outputy",);
    Intent.putextra ("Return-data", true);
    Startactivityforresult (Intent, Crop_request_code);
  }

Let's take a look at an example: first part of the code, the part is extracted from the Internet, and then use it as a tool class.

Configuration file: The layout is very simple, a imagebutton and a button, click can realize the function of image selection, specific implementation according to the effect of the actual use of the
—————————————————————————————————————————————————
Androidmanifest.xml

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  package=" com.cogent.piccut "
  android:versioncode=" 1 "
  android:versionname=" 1.0 ">
 
  <USES-SDK android:minsdkversion= "Ten"/>
 
  <application
    android:icon= "@drawable/ic_launcher"
    Android:label= "@string/app_name" >
    <activity
      android:label= "@string/app_name"
      android:name= ". Piccutactivity "
      android:screenorientation=" Portrait ">
      <intent-filter >
        <action Android:name= "Android.intent.action.MAIN"/>
 
        <category android:name= "Android.intent.category.LAUNCHER" "/>
      </intent-filter>
    </activity>
  </application>
 
</manifest>

—————————————————————————————————————————————————
Java code:

Package com.cogent.piccut;
Import Java.io.File;
Import Java.text.SimpleDateFormat;

Import Java.util.Date;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.graphics.Bitmap;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.Drawable;
Import Android.net.Uri;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.provider.MediaStore;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

Import Android.widget.ImageButton;
  public class Piccutactivity extends activity implements Onclicklistener {private ImageButton img_btn;
  Private Button btn;
  private static final int photo_request_takephoto = 1;//camera private static final int photo_request_gallery = 2;//Select from album private static final int photo_request_cut = 3;//result//Create a file with the current time name = filename Tempfile = new file (environment.getexte RnalstorageDirectory (), Getphotofilename ()); /** called the activity is a.
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
  Init ();
    }//Initialize control private void init () {img_btn = (ImageButton) Findviewbyid (R.ID.IMG_BTN);
    
    BTN = (Button) Findviewbyid (R.ID.BTN);
    Add a listener event to the ImageButton and button Img_btn.setonclicklistener (this);
  Btn.setonclicklistener (this);
    //Click event @Override public void OnClick (View v) {//TODO auto-generated Method Stub switch (V.getid ()) {
      Case R.id.img_btn:showdialog ();

    Break
      Case R.id.btn:showdialog ();
    Break }//Prompt dialog method private void ShowDialog () {new Alertdialog.builder (this). Settitle ("Avatar Settings"). Setpositivebutton ("Camera", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialogi
       Nterface dialog, int which) {     TODO auto-generated Method Stub Dialog.dismiss ();
            Call the system's camera function Intent Intent = new Intent (mediastore.action_image_capture);
            Specifies the storage path Intent.putextra (Mediastore.extra_output,uri.fromfile (tempfile)) of the photo after the camera is photographed;
          Startactivityforresult (Intent, Photo_request_takephoto); }). Setnegativebutton ("album", New Dialoginterface.onclicklistener () {@Override publi c void OnClick (Dialoginterface dialog, int which) {//TODO auto-generated method stub dialog.dism
            ISS ();
            Intent Intent = new Intent (Intent.action_pick, NULL);
            Intent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
          Startactivityforresult (Intent, photo_request_gallery);
  ). Show (); @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generate
D Method Stub
    Switch (requestcode) {case Photo_request_takephoto:startphotozoom (Uri.fromfile (tempfile), 150);

    Break
      Case PHOTO_REQUEST_GALLERY:IF (data!= null) Startphotozoom (Data.getdata (), 150);

    Break
      Case PHOTO_REQUEST_CUT:IF (data!= null) Setpictoview (data);
    Break

  } super.onactivityresult (Requestcode, ResultCode, data);
    private void Startphotozoom (URI uri, int size) {Intent Intent = new Intent ("Com.android.camera.action.CROP");
    Intent.setdataandtype (URI, "image/*");

    Crop is true to set the view that is displayed in the open intent to trim Intent.putextra ("Crop", "true");
    Aspectx Aspecty is a wide-height proportional Intent.putextra ("Aspectx", 1);

    Intent.putextra ("Aspecty", 1);
    Outputx,outputy is the Intent.putextra ("Outputx", size) of the cropped picture;
    Intent.putextra ("Outputy", size);

    Intent.putextra ("Return-data", true);
  Startactivityforresult (Intent, photo_request_cut); //The cropped picture will be displayed to the UI interface with private void SETpictoview (Intent picdata) {Bundle Bundle = Picdata.getextras ();
      if (bundle!= null) {Bitmap photo = bundle.getparcelable ("Data");
      drawable drawable = new bitmapdrawable (photo);
    Img_btn.setbackgrounddrawable (drawable); Use the system's current date to be adjusted as the name of the photo private String Getphotofilename () {Date date = new Date (System.currenttimemillis ())
    ;
    SimpleDateFormat DateFormat = new SimpleDateFormat ("' IMG ' _yyyymmdd_hhmmss");
  return Dateformat.format (date) + ". jpg";

 }
}

Experience Summary: Androi system with the image of the clipping function, the development is as long as the call can be, intent a lot of usage is more practical, but too much, need to use the time to query or usually read more official documents, a lot of code to look at the simple but still have to actually write their own better, Understand a little bit more deeply.

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.