Android photo or album get Avatar (compatible with 4.4 or less, 4.4,5.0,6.0 version)

Source: Internet
Author: User
Tags crop image

First for permissions:

  <uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Com.android.vending.BILLING "/>    <uses-permission android:name=" android.permission.WRITE_EXTERNAL_ STORAGE "/>    <uses-permission android:name=" Android.permission.ACCESS_NETWORK_STATE "/>    < Uses-permission android:name= "Android.permission.READ_PHONE_STATE"/>
Here's the code:
<pre name= "code" class= "Java" >public class Mainactivity extends Activity implements View.onclicklistener {private Relativelayout macountheadiconlayout;private ImageView macountheadicon;//Save picture Local path public static final String Account_ DIR = Environment.getexternalstoragedirectory (). GetPath () + "/account/";p ublic static final String Account_maintrance_ Icon_cache = "icon_cache/";p rivate static final String Imgpath = account_dir + account_maintrance_icon_cache;private stat IC final String image_file_name = "Faceimage.jpeg";p rivate static final String tmp_image_file_name = "Tmp_faceimage.jpeg" ;//constants define public static final int take_a_picture = 10;public static final int select_a_picture = 20;public static final int S Et_picture = 30;public static final int set_album_picture_kitkat = 40;public static final int Selecet_a_picture_after_kika T = 50;private String malbumpicturepath = null; File fileone = null; File Filetwo = null;//version comparison: Is 4.4 and later final Boolean Miskitkat = Build.VERSION.SDK_INT >= BuIld. Version_codes. KITKAT; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); macountheadiconlayout = (relativelayout) Findviewbyid (R.id.account_head_item); Macountheadiconlayout.setonclicklistener (this); Macountheadicon = (ImageView) Findviewbyid (R.id.head_value); Macountheadicon.setonclicklistener (this); File directory = new file (Account_dir); File ImagePath = new file (Imgpath), if (!directory.exists ()) {log.i ("Zou", "Directory.mkdir ()");d Irectory.mkdir ();} if (!imagepath.exists ()) {log.i ("Zou", "Imagepath.mkdir ()"); Imagepath.mkdir ();} Fileone = new File (Imgpath, image_file_name); filetwo = new File (Imgpath, tmp_image_file_name); try {if (!fileone.exists () &&!filetwo.exists ()) {fileone.createnewfile (); Filetwo.createnewfile ();}} catch (Exception e) {}} @Overridepublic void OnClick (View v) {if (V.getid () = = R.id.account_head_item) {New Alertdialog.bui Lder (This). Settitle ("Set Avatar"). Setnegativebutton ("album", New DialoginteRface. Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {if (Miskitkat) { Selectimageuriafterkikat ();} else {Cropimageuri ();}}}). Setpositivebutton ("Camera", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {Intent Intent = new Intent (mediastore.action_image_capture); Intent.putextra (Mediastore.extra_output, Uri.fromfile (New File (Imgpath, Image_file_name)); Startactivityforresult (Intent, take_a_picture); LOG.I ("Zou", "Take_a_picture");}). Show ();}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult ( Requestcode, ResultCode, data); if (Requestcode = = select_a_picture) {if (ResultCode = RESULT_OK && null! = data) {//log.i ("Zou", "under 4.4"); Bitmap Bitmap = Decodeuriasbitmap (Uri.fromfile (New File (Imgpath,tmp_image_file_name))); Macountheadicon.setimagebitmap (bitmap);} else if (ResultCode = = result_canceled) {toast.maketext (mainactivity.this, "Remove avatar Settings", Toast.length_short). Show ();}} else if (Requestcode = = Selecet_a_picture_after_kikat) {if (ResultCode = = RESULT_OK && null! = data) {//LOG.I ("Zou "," 4.4 or more "); Malbumpicturepath = GetPath (Getapplicationcontext (), Data.getdata ()); Cropimageuriafterkikat ( Uri.fromfile (New File (Malbumpicturepath)));} else if (ResultCode = = result_canceled) {toast.maketext (mainactivity.this, "Remove avatar Settings", Toast.length_short). Show ();}} else if (Requestcode = = Set_album_picture_kitkat) {log.i ("Zou", "Result_ok above 4.4"); Bitmap Bitmap = Decodeuriasbitmap (Uri.fromfile (New File (Imgpath, tmp_image_file_name)); Macountheadicon.setimagebitmap (bitmap),//LOG.I ("Zou", "Result_ok above 4.4");//bitmap bitmap = Data.getparcelableextra ("Data");//macountheadicon.setimagebitmap (bitmap);} else if (Requestcode = = take_a_picture) {log.i ("Zou", "Take_a_picture-resultcode:" + ResultCode); if (ResultCode = = RESULT _OK) {Cameracropimageuri (Uri.fromfile (New File (Imgpath, Image_file_name)));} else {Toast.maketext (mainactivity.this , "TakeAvatar settings ", Toast.length_short). Show ();}} else if (Requestcode = = set_picture) {//Photo set Avatar does not consider version//log.i ("Zou", "Set_picture-resultcode:" + ResultCode); Bitmap Bitmap = null;//if (Miskitkat) {//High version//if (null! = data) {//bitmap = Data.getparcelableextra ("data");//showloadin g ();//maccountcontrol.resetgousericon (Bitmap2byte (bitmap), this),//} else {//High version cannot get the picture data through "data" using uri//if ( ResultCode = = RESULT_OK) {//bitmap = Decodeuriasbitmap (Uri.fromfile (New File (Imgpath, Image_file_name)));// Showloading ();//maccountcontrol.resetgousericon (Bitmap2byte (bitmap), this);//}//}//} else {//low version if (ResultCode = = RESULT_OK && NULL! = data) {bitmap = Decodeuriasbitmap (Uri.fromfile (New File (Imgpath, image_file_name)); Macountheadicon.setimagebitmap (bitmap);} else if (ResultCode = = result_canceled) {toast.maketext (mainactivity.this, "Remove avatar Settings", Toast.length_short). Show ();} else {Toast.maketext (Mainactivity.this, "set Avatar Failed", Toast.length_short). Show (); }}}/** <br> Function Description:-------------------of cutting picture method---albums * <br> features detailed description: * <br> Note: */private void Cropimageuri () {Intent Intent = new Intent (Intent.action_get_con TENT, NULL), Intent.settype ("image/*"), Intent.putextra ("crop", "true"), Intent.putextra ("Aspectx", 1); Intent.putextra ("Aspecty", 1), Intent.putextra ("Outputx", 640), Intent.putextra ("Outputy", 640); Intent.putextra (" Scale ", true); Intent.putextra (" Return-data ", false); Intent.putextra (Mediastore.extra_output,uri.fromfile (New File (Imgpath, Tmp_image_file_name))); Intent.putextra ("OutputFormat", Bitmap.CompressFormat.JPEG.toString ()); Intent.putextra ("Nofacedetection", true); No face Detectionstartactivityforresult (intent, select_a_picture);} /** * <br> function Brief: More than 4.4 cropping image method to achieve----------------------album * <br> features detailed description: * <br> NOTE: */@TargetApi ( Build.version_codes. KITKAT) private void Selectimageuriafterkikat () {Intent Intent = new Intent (intent.action_open_document); Intent.addcategory (intent.category_openable); Intent.settype ("image/*"); Startactivityforresult (Intent, SELecet_a_picture_after_kikat);} /** * <br> function Description: Crop picture method Implementation----------------------Camera * <br> Function Details: * <br> Note: * @param uri */private void Cam Eracropimageuri (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, " Image/jpeg "); Intent.putextra (" Crop "," true ") Intent.putextra (" Aspectx ", 1); Intent.putextra (" Aspecty ", 1); Intent.putextra ("Outputx", 640); Intent.putextra ("Outputy", 640); Intent.putextra ("scale", true);//if (Miskitkat) {// Intent.putextra ("Return-data", true);//intent.putextra (Mediastore.extra_output, URI);/} else {Intent.putextra (" Return-data ", false); Intent.putextra (Mediastore.extra_output, URI);//}intent.putextra (" OutputFormat ", Bitmap.CompressFormat.JPEG.toString ()); Intent.putextra ("Nofacedetection", true); Startactivityforresult (Intent, Set_picture);}  /** * <br> function Brief: 4.4 and above modified version of the crop image method to achieve--------------------camera * <br> Function Detailed Description: * <br> Note: * @param uri */private void Cropimageuriafterkikat (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, "Image/jpeg"); Intent.putextra ("CROP", " True "); Intent.putextra (" Aspectx ", 1); Intent.putextra (" Aspecty ", 1); Intent.putextra (" Outputx ", 640);                Intent.putextra ("Outputy", 640); Intent.putextra ("scale", true); if (Build.VERSION.SDK_INT >= build.version_codes.                    LOLLIPOP) {Intent.putextra ("OutputFormat", Bitmap.CompressFormat.JPEG.toString ());                    Intent.putextra ("Nofacedetection", true);                    Intent.putextra (Mediastore.extra_output, URI); Intent.putextra ("Return-data", false);//set to not return data}else{Intent.putextra ("Return-data", t Rue);//set to not return data}startactivityforresult (intent, Set_album_picture_kitkat);} /** * <br> Function Description: * <br> Function Details: * <br> Note: * @param uri * @return */private Bitmap decodeuriasbitmap (Uri u RI) {Bitmap Bitmap = null;try {Bitmap = Bitmapfactory.decodestream (GetconTentresolver (). Openinputstream (URI));} catch (FileNotFoundException e) {e.printstacktrace (); return null;} return bitmap;} /** * <br> function Brief: 4.4 and above how to get pictures * <br> features detailed description: * <br> Note: * @param context * @param URI * @return */@TargetA Pi (build.version_codes. KITKAT) public static String GetPath (final context context, final URI Uri) {Final Boolean iskitkat = Build.VERSION.SDK_INT >= Build.version_codes. kitkat;//Documentproviderif (Iskitkat && documentscontract.isdocumenturi (context, URI)) {// Externalstorageproviderif (Isexternalstoragedocument (URI)) {final String docId = Documentscontract.getdocumentid (uri Final string[] split = Docid.split (":"); final String type = split[0];if ("PRIMARY". Equalsignorecase (Type)) {return Envi Ronment.getexternalstoragedirectory () + "/" + split[1];}} Downloadsproviderelse if (Isdownloadsdocument (URI)) {final String id = documentscontract.getdocumentid (URI); final Uri Contenturi = Contenturis.withappendedid (Uri.parse ("content://downloads/Public_downloads "), long.valueof (ID)), return Getdatacolumn (context, Contenturi, NULL, NULL);} Mediaproviderelse if (Ismediadocument (URI)) {final String docId = Documentscontract.getdocumentid (URI); final string[ ] Split = Docid.split (":"); final String type = split[0]; Uri Contenturi = null;if ("image". Equals (Type)) {Contenturi = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if (" Video ". Equals (Type)) {Contenturi = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if (" Audio ". Equals (type)) { Contenturi = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;} Final String selection = "_id=?"; Final string[] Selectionargs = new string[] {split[1]};return getdatacolumn (context, Contenturi, selection, Selectionarg s);}} Mediastore (and general) else if ("content". Equalsignorecase (Uri.getscheme ())) {//Return the remote Addressif (ISGOOGL Ephotosuri (URI)) return uri.getlastpathsegment (); return Getdatacolumn (context, URI, NULL, NULL);} Fileelse if ("File". Equalsignorecase (Uri.getscheme ())) {return Uri.getpath ();} return null;} public static string Getdatacolumn (context context, Uri Uri, String selection,string[] selectionargs) {cursor cursor = nul l;final String column = "_data"; final string[] projection = {Column};try {cursor = Context.getcontentresolver (). query (Ur I, projection, selection, selectionargs,null); if (cursor! = NULL && Cursor.movetofirst ()) {Final int index = Curso R.getcolumnindexorthrow (column); return cursor.getstring (index);}} Finally {if (cursor! = NULL) Cursor.close ();} return null;} /** * @param URI of the URI to check. * @return Whether The Uri authority is externalstorageprovider. */public static Boolean isexternalstoragedocument (Uri uri) {return "com.android.externalstorage.documents". Equals ( Uri.getauthority ());} /** * @param URI of the URI to check. * @return Whether The Uri authority is downloadsprovider. */public static Boolean isdownloadsdocument (Uri uri) {return "com.android.providers.downloads.documents". Equals ( Uri.getauthority ());} /** * @param uri the URI to check. * @return Whether The Uri authority is mediaprovider. */public static Boolean ismediadocument (Uri uri) {return "com.android.providers.media.documents". Equals ( Uri.getauthority ());} /** * @param URI of the URI to check. * @return Whether The Uri authority is Google Photos. */public static Boolean Isgooglephotosuri (Uri uri) {return "Com.google.android.apps.photos.content". Equals ( Uri.getauthority ());}}


Android photo or album get Avatar (compatible with 4.4 or less, 4.4,5.0,6.0 version)

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.