Android Personal Center Avatar Upload, Image coding and interception example _android

Source: Internet
Author: User
Tags base64

First you need to have network permissions, and then our matching network request is the okhttp that was previously encapsulated.

Very simple and convenient, directly copied in, rely on the package, and then call the method can be.

Here is to convert the picture into Base64.decode (imagestring, Base64.default);

Turn into Base64 code upload. Specific content is also a lot, need to fully understand, or take a little time to see.

Let's look at the simple effect chart:



So everything is available, only the East wind. Directly on the code:

public class Mainactivity extends Appcompatactivity implements View.onclicklistener {private ImageView iv_img;
  Private Button Bt_camera;
  Private Button BT_XIANGCE; private static final int photo_request_carema = 1;//camera private static final int photo_request_gallery = 2;//Select P from album rivate static final int photo_request_cut = 3;//result/* Avatar name/private static final String Photo_file_name = "Temp_pho
  To.jpg ";

  Private File tempfile;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  Load control Initview ();
    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 Sharedpreferences getbitmapfromsharedpreferences ();
    Monitor two buttons, photo album button and camera button Bt_camera.setonclicklistener (this);
Bt_xiangce.setonclicklistener (this);  @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.bt_camera://Activate camera
        Intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE"); To determine if a memory card is available, use it to store if (Hassdcard ()) {tempfile = new File (Environment.getexternalstoragedirectory (), P
          Hoto_file_name);
          Creates a URI uri uri = uri.fromfile (tempfile) from the file;
        Intent.putextra (Mediastore.extra_output, URI);
        //Open an activity with a return value, the request code is Photo_request_carema Startactivityforresult (intent, Photo_request_carema);
      Break
        Case R.ID.BT_XIANGCE://Activate system gallery, select a picture Intent intent1 = new Intent (Intent.action_pick);
        Intent1.settype ("image/*");
        An activity with a return value is opened, and the request code is Photo_request_gallery Startactivityforresult (intent1, photo_request_gallery);
    Break }/* * To determine whether sdcard is mounted/private Boolean hassdcard () {//To determine whether the SD card is installed media_mounted if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {return true;
    else {return false; }/* * Cut picture/private void crop (Uri uri) {//Crop picture Intent Intent Intent = new Intent ("Com.android.camer
    A.action.crop ");
    Intent.setdataandtype (URI, "image/*");
    Intent.putextra ("Crop", "true");
    The proportion of the cropping box, 1:1 Intent.putextra ("Aspectx", 1);
    Intent.putextra ("Aspecty", 1);
    The size of the output picture after cropping Intent.putextra ("Outputx", 250);

    Intent.putextra ("Outputy", 250); Intent.putextra ("OutputFormat", "JPEG");//Picture Format Intent.putextra ("Nofacedetection", true);//Cancel Face recognition Intent.putextra
    ("Return-data", true);
  An activity with a return value is opened, and the request code is Photo_request_cut Startactivityforresult (intent, photo_request_cut); }/** * * @param requestcode * @param resultcode * @param data/@Override protected void Onactivit Yresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Photo_requesT_gallery) {//The data returned from the photo album (!= null) {//Get the picture's full path uri uri = Data.getdata ();
      Crop (URI); "Else if (Requestcode = = Photo_request_carema) {//data returned from the camera if (Hassdcard ()) {crop (Uri.fromfi
      Le (tempfile)); else {toast.maketext (mainactivity.this, "No storage card found, unable to store photo!")
      ", Toast.length_short). Show ();  {/Else if (Requestcode = = photo_request_cut) {//The data returned from the cut picture if (the date!= null) {Bitmap Bitmap =
        Data.getparcelableextra ("Data");
        /** * Get Picture * * * IV_IMG.SETIMAGEBITMAP (bitmap);
      Save to Sharedpreferences savebitmaptosharedpreferences (bitmap);
      try {//delete temporary files tempfile.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); The first step: compress the bitmap into the byte array output stream Bytearrayoutputstream bytearrayoutputstream Bytearrayoutputstream = new
    Bytearrayoutputstream ();
    Bitmap.compress (Bitmap.CompressFormat.PNG, Bytearrayoutputstream);
    Step two: Use Base64 to convert the data in the byte array output stream to string byte[] ByteArray = Bytearrayoutputstream.tobytearray ();
    String imagestring = new String (base64.encodetostring (ByteArray, Base64.default)); Step three: Keep the string to sharedpreferences sharedpreferences sharedpreferences = getsharedpreferences ("testsp", Context.MODE
    _private);
    Sharedpreferences.editor Editor = Sharedpreferences.edit ();
    Editor.putstring ("image", imagestring);

    Editor.commit ();
  Upload Avatar Setimgbystr (imagestring, ""); /** * Upload avatar * @param imgstr * @param imgname * * public void Setimgbystr (string imgstr, String imgname)
    {//Here is Avatar interface, through POST request, Mosaic interface address and ID, upload data.
    String url = "http://here is the interface address (the specific receive format to see how to give the background)"; Map<string, string> params = new hashmap<string, string> ();
    Params.put ("id", "11111111");//11111111 Params.put ("Data", IMGSTR); Okhttp.postasync (URL, params, new Okhttp.datacallback () {@Override public void requestfailure (Request request
      , IOException e) {log.i ("Upload failed", "failure" + request.tostring () + e.tostring ()); @Override public void requestsuccess (String result) throws Exception {Toast.maketext (mainactivity.t
        His, "Upload success", Toast.length_short. Show ();
      LOG.I ("Upload success", result);
  }
    }); ///Get picture from sharedpreferences private void Getbitmapfromsharedpreferences () {sharedpreferences sharedpreferences=get
    Sharedpreferences ("testsp", context.mode_private);
    Step One: Remove bitmap string imagestring=sharedpreferences.getstring ("image", "") in the form of strings;
    Step Two: Convert the string into Bytearrayinputstream byte[] bytearray= base64.decode (imagestring, Base64.default) using Base64; if (bytearray.length==0) {Iv_img.setimagereSource (R.mipmap.ic_launcher);

      }else{bytearrayinputstream bytearrayinputstream=new Bytearrayinputstream (ByteArray);
      The third step: using Bytearrayinputstream to generate Bitmap Bitmap bitmap= bitmapfactory.decodestream (Bytearrayinputstream);
    Iv_img.setimagebitmap (bitmap);


 }

  }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.