Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/39994913
Recently removed from the previous project a common module, where it is necessary to record, is the android to get pictures and crop pictures, how? This function is not very commonly used ah, you casually open an app, as long as it has a registration function will have the ability to set up avatars, especially in the content-based app more common, then how these features are implemented? Today, the record here is good, to prevent future projects will also be used, it is directly used.
1. Get pictures by photo or Atlas (no clipping required)
This way to get the picture is compared, because do not set the image clipping function, it is possible because the picture is too large, resulting in oom, but this way is also necessary to talk about, and its way to get pictures of two, one is to call the system camera real-time shooting a picture, 20 open the device has a gallery, Select a picture in the gallery. Both of these approaches are a truth, nothing more than invoking the system through intent. The following is the source code, the first is the image selection method of activity, the activity is set to dialog mode, need to set up a bit.
Layout file/res/layout/activity_select_photo.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:gravity=" Center_horizont Al "> <linearlayout android:id=" @+id/dialog_layout "android:layout_width=" Fill_parent "Andro id:layout_height= "Wrap_content" android:layout_alignparentbottom= "true" android:layout_marginleft= "10dip" android:layout_marginright= "10dip" android:gravity= "center_horizontal" android:orientation= "vertical" & Gt <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:background= "@drawable/select_photo_up_bg" android:orientation= "vertical" Android:paddingbott Om= "5DP" android:paddingtop= "5DP" > <button android:id= "@+id/btn_take_photo" Android:lAyout_width= "Fill_parent" android:layout_height= "35DP" android:background= "@drawable/select_ PHOTO_BG "android:text=" Take photos Select "android:textstyle=" bold "/> <view Android:layout_width= "Fill_parent" android:layout_height= "0.5px" android:background= "#82 8282 "/> <button android:id=" @+id/btn_pick_photo "Android:layout_width=" fil L_parent "android:layout_height=" 35DP "android:layout_margintop=" 0dip "Androi d:background= "@drawable/select_photo_bg" android:text= "album select" android:textstyle= "bold"/> </LinearLayout> <button android:id= "@+id/btn_cancel" android:layout_width= "fi Ll_parent "android:layout_height=" 35DP "android:layout_margintop=" 20dip "Android:backgrou nd= "@drawable/select_phoTO_BG "android:paddingbottom=" 5DP "android:paddingtop=" 5DP "android:text=" Cancel " Android:textcolor= "#ffff0000" android:textstyle= "bold"/> </LinearLayout></RelativeLayout>
Next is the code selectphotoactivity that gets the image activity:
public class Selectphotoactivity extends Activity implements Onclicklistener {/** take pictures with camera get picture */public static final int SE Lect_pic_by_tack_photo = 1;/** use picture in album */public static final int select_pic_by_pick_photo = 2;/** turn on camera */private Button b tn_take_photo;/** Open Atlas */private button btn_pick_photo;/** Cancel */private button btn_cancel;/** get to the picture path */private String pi Cpath;private Intent lastintent;private Uri photouri;/** Get the image path from Intent KEY */public static final String Key_photo_path = " Photo_path "; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_select_photo); Btn_take_photo = (Button) Findviewbyid (R.id.btn_take_photo); btn_ Pick_photo = (Button) Findviewbyid (r.id.btn_pick_photo); btn_cancel = (Button) Findviewbyid (R.id.btn_cancel); Lastintent = Getintent (); Btn_take_photo.setonclicklistener (this), Btn_pick_photo.setonclicklistener (this); Btn_ Cancel.setonclicklistener (this);} @Overridepublic void OnClick (View v) {SWITCH (V.getid ()) {case R.id.btn_take_photo://Open camera Takephoto (); Break;case R.id.btn_pick_photo://Open Atlas Pickphoto (); break; Case R.id.btn_cancel://Cancel Operation This.finish (); break;default:break;}} /** * Take pictures */private void Takephoto () {//before performing a photo shoot, you should first determine if the SD card exists string sdstate = Environment.getexternalstoragestate (); if ( Sdstate.equals (environment.media_mounted)) {Intent Intent = new Intent (mediastore.action_image_capture);//" Android.media.action.IMAGE_CAPTURE "/*** * need to explain, the following operation using a camera to take pictures, photos after the photo will be stored in the album in this way there is a good thing is to get the picture is the original photo after * If it is not practical contentvalues store photo path, the picture obtained after taking pictures for the thumbnail is not clear */contentvalues values = new Contentvalues ();p Hotouri = This.getcontentresolver (). Insert (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent.putextra ( Android.provider.MediaStore.EXTRA_OUTPUT, Photouri); Startactivityforresult (Intent, Select_pic_by_tack_photo);} else {Toast.maketext (Getapplicationcontext (), "Memory card not Present", Toast.length_short). Show ();}} /*** * Take picture from album */private Void Pickphoto () {Intent Intent = new Intent (); intent.seTtype ("image/*"); Intent.setaction (intent.action_get_content); Startactivityforresult (Intent, SELECT_PIC_BY_PICK_ PHOTO);} @Overridepublic boolean ontouchevent (Motionevent event) {finish (); return super.ontouchevent (event);} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (ResultCode = = Activity.result _OK) {Dophoto (requestcode, data);} Super.onactivityresult (Requestcode, ResultCode, data);} /** * After selecting the picture, get the path of the picture * * @param requestcode * @param data */private void Dophoto (int requestcode, Intent data) {if (reques Tcode = = Select_pic_by_pick_photo) {//from the album to take pictures, some phones have unusual situation, please note if (data = = null) {Toast.maketext (Getapplicationcontext (), " Error selecting picture file ", Toast.length_short). Show (); return;} Photouri = Data.getdata (), if (Photouri = = null) {Toast.maketext (Getapplicationcontext (), "Error selecting picture file", Toast.length_ Short). Show (); return;}} String[] Pojo = {MediaStore.Images.Media.DATA}; cursor cursor = managedquery (Photouri, pojo, NULL, NULL, NULL); if (cursor! = NULL) {int columnindex =Cursor.getcolumnindexorthrow (Pojo[0]); Cursor.movetofirst ();p Icpath = cursor.getstring (columnindex); Cursor.close ( );} if (Picpath! = null&& (Picpath.endswith (". png") | | | Picpath.endswith (". PNG ") | | Picpath.endswith (". jpg") | | Picpath.endswith (". JPG ")) {Lastintent.putextra (Key_photo_path, Picpath); Setresult (ACTIVITY.RESULT_OK, lastintent); Finish ();} else { Toast.maketext (Getapplicationcontext (), "Select Picture file is incorrect", Toast.length_short). Show ();}}
Because this activity is to be set to dialog mode, it needs to be set up in the manifest file Style,/res/values/styles.xml to add the following:
<!--Choose the style of the activity of the photo, take the style of the dialog box--<style name= "Animbottom" parent= "@android: Style/animation" > < ; Item Name= "Android:windowenteranimation" > @anim/push_bottom_in</item> <item name= "Android: Windowexitanimation "> @anim/push_bottom_out</item> </style> <style name=" Dialogstylebottom " Parent= "Android:Theme.Dialog" > <item name= "Android:windowanimationstyle" > @style/animbottom</item> <item name= "Android:windowframe" > @null </item> <!--bezel-<item name= "Android:win Dowisfloating ">false</item> <!--is on the activity--<item name=" Android:windowistransluce NT ">true</item> <!--Translucent--<item name=" Android:windownotitle ">true</item> <!--Untitled-<item name= "Android:windowbackground" > @android:color/transparent</item> < ;! --Clear background--<item name= "AndroiD:backgrounddimenabled ">true</item> <!--Blur--</style>
Under the Activity node, set this style:
<activity android:name= "com.example.croppictrue.SelectPhotoActivity" android:screenorientation= " Portrait " android:theme=" @style/dialogstylebottom "> </activity>
Add Permissions:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
The results are as follows:
2. Get pictures by photo or Atlas (need to be cropped)
The first way to get a picture is not trimmed, but most of the project needs are to be cropped and then used, such as modifying the user's avatar and so on. So, here's the code for the cropped picture:
public class Croppictureactivity extends Activity {/** ImageView object */private ImageView iv_photo;private string[] items = n EW string[]{"Select local picture", "Take Photo"};/** Avatar name */private static final String image_file_name = "image.jpg";/** Request code */private static Final int image_request_code = 0;private static final int camera_request_code = 1;private static final int result_request_ CODE = 2; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_crop); Iv_photo = (ImageView) Findviewbyid (R.id.iv_photo); iv_ Photo.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {showDialog ();}});} /** * Displays the selection dialog box */private void ShowDialog () {new Alertdialog.builder (this). Settitle ("Set Avatar"). Setitems (Items, new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {switch (which) { Case 0:intent intentfromgallery = new Intent (); Intentfromgallery.settype ("image/*"); Set File type IntentfromgAllery.setaction (intent.action_get_content); Startactivityforresult (Intentfromgallery,image_request_code); break Case 1:intent intentfromcapture = new Intent (mediastore.action_image_capture);//Determine if the memory card is usable, and can be used to store string state = Environment.getexternalstoragestate (); if (State.equals (environment.media_mounted)) {File Path = Environment.getexternalstoragepublicdirectory (ENVIRONMENT.DIRECTORY_DCIM); File File = new file (path, image_file_name); Intentfromcapture.putextra (mediastore.extra_output,uri.fromfile (file));} Startactivityforresult (Intentfromcapture,camera_request_code); break;}}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {Dialog.dismiss ();}}). Show ();} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//Result code is not equal to cancel when if (ResultCode! = RES ult_canceled) {switch (requestcode) {case Image_request_code:startphotozoom (Data.getdata ()); Break;case CAMERA_ Request_code://Determine if the memory card canstring state = Environment.getexternalstoragestate (), if (State.equals (environment.media_mounted)) {File path = Environment.getexternalstoragepublicdirectory (ENVIRONMENT.DIRECTORY_DCIM); File Tempfile = new file (path, image_file_name); Startphotozoom (Uri.fromfile (Tempfile));} else {toast.maketext (getapplicationcontext), "No memory card found, no photos saved!" ", Toast.length_short). Show ();} Break;case Result_request_code://Image Zoom complete if (data! = null) {Getimagetoview (data);} Break;}} Super.onactivityresult (Requestcode, ResultCode, data);} /** * Cropping image method Implementation * * @param uri */public void Startphotozoom (Uri uri) {Intent Intent = new Intent ("Com.android.camera.actio N.crop "); Intent.setdataandtype (URI," image/* ");//Set Crop Intent.putextra (" CROP "," true ");//Aspectx Aspecty is the ratio of Intent.putextra ("Aspectx", 1), Intent.putextra ("Aspecty", 1);//Outputx outputy is the cropped picture width Intent.putextra (" Outputx ", 340); Intent.putextra (" Outputy ", 340); Intent.putextra (" Return-data ", true); Startactivityforresult (Intent , Result_request_code);} /** * WarrantyThe picture data after the clip is saved * * @param picdata */private void Getimagetoview (Intent data) {Bundle extras = Data.getextras (); if (extras! = NULL) {Bitmap photo = extras.getparcelable ("Data");D rawable drawable = new Bitmapdrawable (this.getresources (), photo); Iv_photo.setimagedrawable (drawable);}}}
:
In this activity for the sake of simple processing, I did not select the picture when the start of a dialog-style activity, directly a normal dialog box prompts the user to choose, the effect may be. In fact, the implementation of the principle is relatively simple, the realization of the picture is to cut a intent request, call the device all have the clip picture function of the app to cut the picture, my device in addition to the Android system comes with the library, but also equipped with "Quick View" this app, The app also comes with a picture-clipping feature, all when a good image is selected, a selection prompt appears, and the user can choose which app to use to trim the picture, based on the prompts.
The above code are tested on the simulator, because the simulator is not good for the camera support, so there is no demo to open the camera to take pictures, interested friends can first download the demo source, run on the phone to try the effect how, if the omission, welcome everyone to criticize correct!
Please download the source code here
Android photo selection and picture clipping