First of all we need to have network permissions, and then we match the network request is the previously encapsulated okhttp,okhttp
Very simple and convenient, directly copied in, rely on the package, and then call the method.
Here is the picture converted into Base64.decode (imagestring, Base64.default);
Switch to BASE64 encoded upload. Specific content also a lot, need to fully understand, or take some time to look slowly.
First look at the simple:
Then everything has, only the east wind. Directly on the code:
Public class mainactivity extends appcompatactivity implements View . Onclicklistener { PrivateImageView iv_img;PrivateButton Bt_camera;PrivateButton BT_XIANGCE;Private Static Final intPhoto_request_carema =1;//Photo Private Static Final intPhoto_request_gallery =2;//Select from the album Private Static Final intPhoto_request_cut =3;//Results / * Avatar name * / Private Static FinalString Photo_file_name ="Temp_photo.jpg";PrivateFile Tempfile;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Load ControlInitview (); }Private void Initview() {iv_img = (ImageView) Findviewbyid (r.id.iv_img); Bt_camera = (Button) Findviewbyid (R.id.bt_camera); BT_XIANGCE = (Button) Findviewbyid (R.ID.BT_XIANGCE);//Get pictures from SharedpreferencesGetbitmapfromsharedpreferences ();//Monitor two buttons, photo album button and camera buttonBt_camera.setonclicklistener ( This); Bt_xiangce.setonclicklistener ( This); }@Override Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.bt_camera://Activate cameraIntent Intent =NewIntent ("Android.media.action.IMAGE_CAPTURE");//Determine if the memory card is usable and can be used for storage if(Hassdcard ()) {tempfile =NewFile (Environment.getexternalstoragedirectory (), photo_file_name);//Create a URI from the fileUri uri = uri.fromfile (tempfile); Intent.putextra (Mediastore.extra_output, URI); }//Open an activity with a return value, the request code is Photo_request_caremaStartactivityforresult (Intent, Photo_request_carema); Break; CaseR.ID.BT_XIANGCE://Activate system gallery, select a pictureIntent intent1 =NewIntent (Intent.action_pick); Intent1.settype ("image/*");//Open an activity with a return value, the request code is photo_request_galleryStartactivityforresult (Intent1, photo_request_gallery); Break; } }/ * * Determine if sdcard is mounted */ Private Boolean Hassdcard() {//To determine if SD card hand is installed media_mounted if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {return true; }Else{return false; } }/ * * Cut pictures */ Private void Crop(URI Uri) {//crop image IntentIntent Intent =NewIntent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI,"image/*"); Intent.putextra ("Crop","true");//ratio of crop box, 1:1Intent.putextra ("Aspectx",1); Intent.putextra ("Aspecty",1);//The size of the output picture after croppingIntent.putextra ("Outputx", -); Intent.putextra ("Outputy", -); Intent.putextra ("OutputFormat","JPEG");//Picture formatIntent.putextra ("Nofacedetection",true);//Remove face recognitionIntent.putextra ("Return-data",true);//Open an activity with a return value, the request code is photo_request_cutStartactivityforresult (Intent, photo_request_cut); }/** * * @param requestcode * @param resultcode * @param Data * * @Override protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {if(Requestcode = = photo_request_gallery) {//Data returned from the album if(Data! =NULL) {//Get the full path of the pictureUri uri = Data.getdata (); Crop (URI); } }Else if(Requestcode = = Photo_request_carema) {//data returned from the camera if(Hassdcard ()) {Crop (Uri.fromfile (tempfile)); }Else{Toast.maketext (mainactivity). This,"No memory card found, no photos saved!" ", Toast.length_short). Show (); } }Else if(Requestcode = = photo_request_cut) {//data returned from the cut image if(Data! =NULL) {Bitmap Bitmap = Data.getparcelableextra ("Data");/** * Get pictures * *Iv_img.setimagebitmap (bitmap);//Save to SharedpreferencesSavebitmaptosharedpreferences (bitmap); }Try{//Delete temporary filesTempfile.delete (); }Catch(Exception e) {E.printstacktrace (); } }Super. Onactivityresult (Requestcode, ResultCode, data); }//Save picture to Sharedpreferences Private void savebitmaptosharedpreferences(Bitmap Bitmap) {//Bitmap Bitmap=bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher); ///First step: Compress bitmap into byte array output stream BytearrayoutputstreamBytearrayoutputstream Bytearrayoutputstream =NewBytearrayoutputstream (); Bitmap.compress (Bitmap.CompressFormat.PNG, the, Bytearrayoutputstream);///Step two: Convert data from a byte array output stream to a string using Base64 byte[] ByteArray = Bytearrayoutputstream.tobytearray (); String imagestring =NewString (Base64.encodetostring (ByteArray, Base64.default));//Step Three: Keep the string to SharedpreferencesSharedpreferences sharedpreferences = getsharedpreferences ("TESTSP", context.mode_private); Sharedpreferences.editor Editor = Sharedpreferences.edit (); Editor.putstring ("Image", imagestring); Editor.commit ();//upload avatarSetimgbystr (Imagestring,""); }/** * Upload avatar * @param imgstr * @param imgname * * Public void Setimgbystr(String imgstr, String imgname) {//Here is the Avatar interface, via POST request, splicing interface address and ID, upload data. String URL ="HTTP//here is the interface address (the specific reception format to see how to give the background)"; map<string, string> params =NewHashmap<string, string> (); Params.put ("id","11111111");//11111111Params.put ("Data", IMGSTR); Okhttp.postasync (URL, params,NewOkhttp.datacallback () {@Override Public void requestfailure(Request request, IOException e) {LOG.I ("Upload failed","Failed"+ request.tostring () + e.tostring ()); }@Override Public void requestsuccess(String result)throwsException {toast.maketext (mainactivity. This,"Upload succeeded", Toast.length_short). Show (); LOG.I ("Upload succeeded", result); } }); }//Get pictures from Sharedpreferences Private void getbitmapfromsharedpreferences() {Sharedpreferences sharedpreferences=getsharedpreferences ("TESTSP", context.mode_private);//First step: Take out the string form of the bitmapString imagestring=sharedpreferences.getstring ("Image","");///Step Two: Convert a string to Bytearrayinputstream using Base64 byte[] bytearray= Base64.decode (imagestring, Base64.default);if(bytearray.length==0) {Iv_img.setimageresource (r.mipmap.ic_launcher); }Else{Bytearrayinputstream bytearrayinputstream=NewBytearrayinputstream (ByteArray);//Step three: Generate Bitmap with BytearrayinputstreamBitmap bitmap= Bitmapfactory.decodestream (Bytearrayinputstream); Iv_img.setimagebitmap (bitmap); } }}
Android Personal Center Avatar Upload, image encoding and interception