Android implements crop pictures and set avatar _android from local gallery/camera

Source: Internet
Author: User
Tags mkdir

Play QQ or micro-letter of the Basin friends know that these chat tools to set the avatar, the general solution is to choose from the local image gallery or camera photos, and then according to their favorite interception of pictures. The above process has been achieved, the last step I added to the capture of good pictures in the local operation to save the avatar. For everyone's needs, the following cloud-Habitat community small set up the complete code for your reference.

First to show you the effect of the picture:

Code section:

Layout code (is actually two buttons and a imageview to display the avatar)

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:layout_width= "Match_ Parent "
android:layout_height=" match_parent "
android:orientation=" vertical ">
<imageview
Android:id= "@+id/imageview"
android:layout_width= "wrap_content"
android:layout_height= "Wrap_content"
/>
<button
android:id= "@+id/buttonlocal"
android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= local album select Avatar "/>
<button android:id=
" @+id/ Buttoncamera "
android:layout_width=" wrap_content "
android:layout_height=" Wrap_content "
android: text= "mobile phone photo selection"/>

Body Code:

public class Mainactivity extends Appcompatactivity {/* avatar File/private static final String Image_file_name = "Temp_head
_image.jpg "; /* Request Identification code */private static final int code_gallery_request = 0xa0;//local private static final int code_camera_request = 0XA1;
Photo private static final int code_result_request = 0xa2;//Final cropped result//cropped after the picture's width (x) and High (Y), 480 squared.
private static int output_x = 600;
private static int output_y = 600;
Private ImageView headimage = null; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Headimage = (ImageView) Findviewbyid (R.id.imageview);
Button buttonlocal = (button) Findviewbyid (r.id.buttonlocal);
Buttonlocal.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
Choseheadimagefromgallery ();
}
});
Button Buttoncamera = (button) Findviewbyid (R.id.buttoncamera); Buttoncamera.setonclicklistener (New View.onclicklistener () {@Override public voiD OnClick (View v) {choseheadimagefromcameracapture ();}}); //Select Picture from local album as Avatar private void Choseheadimagefromgallery () {Intent intentfromgallery = new Intent ();//Set File type Intentfro
Mgallery.settype ("image/*");//Choose Picture Intentfromgallery.setaction (intent.action_get_content); If you want to get the data returned after the new open activity closes in the activity,//You need to use the Startactivityforresult provided by the system (Intent intent,int Requestcode)
Methods open new Activity Startactivityforresult (Intentfromgallery, code_gallery_request); //Start mobile camera take photos as Avatar private void Choseheadimagefromcameracapture () {Intent intentfromcapture = new Intent (mediastore.act
Ion_image_capture); Determine if the memory card is available and store the photo file if (Hassdcard ()) {Intentfromcapture.putextra (Mediastore.extra_output, Uri. FromFile (
Environment. getExternalStorageDirectory (), image_file_name));
} startactivityforresult (Intentfromcapture, code_camera_request); @Override protected void Onactivityresult (int requestcode, int resultcode, Intent Intent) {//user does not have a valid set operation, returns if (ResU Ltcode = = result_canceled) {//Cancel toAst.maketext (Getapplication (), "Cancel", Toast.length_long). Show ();
Return Switch (requestcode) {case code_gallery_request://if it is from a local Croprawphoto (Intent.getdata ());//crop the picture break directly; Code_ Camera_request:if (Hassdcard ()) {File Tempfile = new file (Environment.getexternalstoragedirectory (), Image_file_name)
;
Croprawphoto (Uri.fromfile (tempfile));
else {Toast.maketext (getapplication (), "No sdcard!", Toast.length_long). Show ();
Case Code_result_request:if (Intent!= null) {Setimagetoheadview (intent);//Set Picture box} break;
} super.onactivityresult (Requestcode, ResultCode, intent); /** * Crop the original picture */public void Croprawphoto (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); Inten
T.setdataandtype (URI, "image/*");
Insert the cropped data inside//Set the cropping Intent.putextra ("crop", "true");
Aspectx, Aspecty: Wide-high ratio Intent.putextra ("Aspectx", 1);
Intent.putextra ("Aspecty", 1);
OUTPUTX, Outputy: Cut the picture wide high Intent.putextra ("Outputx", output_x);
Intent.putextra ("Outputy", output_y);Intent.putextra ("Return-data", true);
Startactivityforresult (Intent, code_result_request); 
/** * Extracts the image data after saving the cropping, and sets the view/private void Setimagetoheadview (Intent Intent) {Bundle extras = Intent.getextras (); if (extras!= null) {Bitmap photo = extras.getparcelable ("data"); Headimage.setimagebitmap (photo); <br>//New
The folder first chooses the path and then calls the MkDir function is now the Ask folder under the root directory file NF = new file (environment.getexternalstoragedirectory () + "/ask");
Nf.mkdir (); <br>//Create okkk.jpg files under the Ask folder under root directory file F = new file (environment.getexternalstoragedirectory () + "/ask", "OKKK.J
PG ");
FileOutputStream out = null; Try {<br><br>//Open the output stream to fill the picture data into the file out = new FileOutputStream (f); Photo.compress (Bitmap.compressformat.
PNG, N, out); try {out.flush (); Out.close ();} catch (IOException e) {e.printstacktrace ();}}
catch (FileNotFoundException e) {e.printstacktrace ();}} }/** * Check whether the device exists sdcard tool method */public static Boolean Hassdcard () {String state = Environment.getexternalstoraGestate ();
if (State.equals (environment.media_mounted)) {//has a stored sdcard return true;} else {return false;}} }

Because it involves file read and write, to add two permissions!!!

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

About this article for you to introduce the Android implementation from the Local gallery/camera to cut pictures and set the picture of the relevant knowledge to introduce you here, I hope to help you!

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.