Android Development: Get photo albums, photos, upload servers, read photos from the server

Source: Internet
Author: User

Article Directory

    • An overall function description
    • Two-function implementation
      • 1 getting pictures
      • 2 uploading to the server and saving
      • 3 Get the picture from the server and show
      • Accessibility tools in the 4Common class

I. Overall function description

Get the picture by selecting a picture from the album or taking a photo, then uploading the image to the server and reading the image from the server.

Two. function realization 1.1 getting pictures

(1) Normally, there are two ways to do this:

    • Select a picture from the album
      The principle of this way is relatively simple, is to get photos from the SDK, turn to byte reproduction bitmap object for display.

    • Take photos to get pictures
      Photo capture of the principle is the first photo storage, and then read, and from the album to select the same principle of the picture.

(2) Realization:
The following is the code to implement the feature, for some unknown reason, the way the picture was photographed has been a problem: Unable to load this picture. Solve the problem, always can not solve, and then lay aside. The focus of this article is still put in the second part, about uploading to the server, the first part also needs to be further improved, about the selection and processing of pictures, recommended a leaf floating boat article.

    • The first is to click on the avatar to pop up a dialog to choose how to read the picture:
 Privatecharsequence []its = {"Take photos","Select from album"};//upload avatarHeadimageview.setonclicklistener (NewView.onclicklistener () {@Override  Public void OnClick(View v) {NewAlertdialog.builder (modiuserinfoactivity. This). Settitle ("Change your Avatar"). Setitems (ITS,NewDialoginterface.onclicklistener () {@Override                     Public void OnClick(Dialoginterface Dialog,intwhich) {Intent Intent =NewIntent ();Switch(which) { Case 0://photo, no implementation of the part, temporarily do not paste the code, in fact, thought should not be difficult, but the problem has not been solved.                              Break; Case 1://Select from albumIntent.setaction (intent.action_get_content);//action_open_documentIntent.addcategory (intent.category_openable); Intent.settype ("image/*");//intent.putextra ("Return-data", true);//Return Data                            //intent.putextra ("Crop", "true");//croppingStartactivityforresult (Intent,select_pic);//Start activity, rewrite Onactivityresult to get results                             Break;            }}). Create (). Show ();    }        }); }
    • And then we're working on the image data.
@Overrideprotected void Onactivityresult(intRequestcode,intResultCode, Intent data) {if(ResultCode! = RESULT_OK)return;Switch(Requestcode) { CaseSelect_pic://albums              //Contentresolver resolver = Getcontentresolver ();              //Photo's original resource address              //Uri Originaluri = Data.getdata ();              //LOG.I ("Originaluri", originaluri+ "");Bitmap photo =NULL;//Try              // {Photo = Data.getparcelableextra ("Data");//photo = Bitmapfactory.decodestream (Resolver.openinputstream (Originaluri));               if(photo!=NULL) {headimage = Common.zoombitmap (Photo, -, -);//Scaled, can be ignoredUsercontroller.updateheadimage (UserId, Headimage, Handler);//Upload server update, post codePhoto.recycle ();//Recycling}//headimageview.setimagebitmap (headimage);            /*}catch (IOException e) {e.printstacktrace (); }*/                Break; CaseSelect_camera://camera, the following code write a lot, but there is always a problem ~               Try{//Start Gallery to edit this photo                   //final Intent Intent = common.getcropimageintent (Uri.fromfile (Photofile));                   //startactivityforresult (Intent, select_pic);Intent Intent =NewIntent ("Com.android.camera.action.CROP");//TrimIntent.setdataandtype (Photofile,"image/*"); Intent.putextra ("Scale",true);//Set width to height ratioIntent.putextra ("Aspectx",1); Intent.putextra ("Aspecty",1); Intent.putextra ("Outputx", the); Intent.putextra ("Outputy", the); Intent.putextra (Mediastore.extra_output, photofile);//toast.maketext (Modiuserinfoactivity.this, photofile.tostring (), Toast.length_short). Show ();                   //Broadcast Refresh albumIntent INTENTBC =NewIntent (Intent.action_media_scanner_scan_file); Intentbc.setdata (Photofile); This. Sendbroadcast (INTENTBC); Startactivityforresult (Intent, Crop_photo);//Set crop parameter display picture to ImageView}Catch(Exception e)               {E.printstacktrace (); } Break; CaseCrop_photo:Try{//image parsed into bitmap objectBitmap Bitmap = Bitmapfactory.decodestream (Getcontentresolver (). Openinputstream (Photofile));//toast.maketext (Modiuserinfoactivity.this, imageuri.tostring (), Toast.length_short). Show ();Headimage = Common.zoombitmap (Bitmap, -, -);               Usercontroller.updateheadimage (UserId, Headimage, Handler); }Catch(FileNotFoundException e)               {E.printstacktrace (); } Break;default: Break; }    }

OK, according to the above code, select photos from the album and cropping is no problem, as to the picture of some processing, you can refer to a leaf floating boat blog.

1.2 Upload to server and save

Look at a lot of information, the way is either the kind of upload files that kind of look particularly complicated way, see I really big head. Later found several versions of their own failed to achieve the 1.1 captured images uploaded to the server. Then I think about the HTTP request is not the bytes sent, then I turn the picture into bytes can pass, another problem, sometimes we do not just send a picture in the past, there may be other information, such as a form or an ID, in short, the data to be transmitted is more than just pictures. Before transmitting the data through the JSON or map into a String and then to byte[] implementation, now the transmission is the picture + other data, the idea is: Picture->string, and then packaged with other data into json->string-> Byte[]->bitmap.

    • Client
      Now go ahead and write 1.1 of the code used in the Usercontroller.updateheadimage (UserId, Headimage, Handler).
/** * Save Avatar * @param userId * @param handler * @param Image */  Public Static void Updateheadimage(FinalString UserId,FinalBitmap image,FinalHandler Handler) {NewThread () {@Override             Public void Run() {Jsonobject Jsonobject =NewJsonobject ();Try{Jsonobject.put ("UserId", userId);//Turn bitmap into a string, which is actually an encryption process. There will be code for common.bitmap2string () later. Jsonobject.put ("Userimagecontent", common.bitmap2string (image)); String content = string.valueof (jsonobject);/** * Request address * /String URL = configmodel.getserverurl () +"User/updateimage"; String result = Common.httppost (url,content);//post Request Server: Data content, request path URL. This function is also written in the common class, in fact, a little encapsulation of the post request process, easy to reuse. LOG.I ("Result", result);/** * Server return results * Continue to do something .... * *Message message =NewMessage (); Bundle bundle =NewBundle (); Bundle.putstring ("Result", result);                    Message.setdata (bundle);                    Message.what = R.id.save_user_image_result;                Handler.sendmessage (message); }Catch(Exception e)    {}}}.start (); }
    • Server-side
      The client encrypts the picture as a string, and the server needs to decode it to get the picture.
//The first step, the data flow string, itself encapsulated into a read function, easy to reuse;String streamin = Readstream.read (NewBufferedinputstream (Request.getinputstream ()));//jsonobject object = Jsonobject.fromobject (streamin). Getjsonobject ("user");Jsonobject object = Jsonobject.fromobject (streamin);//string Turn JSONString userId = object.getstring ("UserId"); String userimagecontent = object.getstring ("Userimagecontent");//Get the image data//.. Other steps omitted//.. For example, to determine whether a new image, such as the generation of image id Imgid = Tool.getuuid ();///second step to convert the image data string to bitmapbyte[] bitmaparray= Base64.decode (imagecontent);Try{File ImageFile =NewFile (Headimagepath);if(!imagefile.exists ()) imagefile.mkdirs ();//Create an output streamFileOutputStream OutStream =NewFileOutputStream (Imagefile.getpath () +"\\"+imgid+". png");//Write DataOutstream.write (Bitmaparray);//Close output streamOutstream.close (); }Catch(IOException e) {System.out.println (e);}

This is the perfect way to upload the client's image and data to the server. The following part is from the server to get pictures and data back to the client, with the previous part of the idea, then this part is easy to achieve, the opposite can be.

1.3 Get the picture from the server and show
    • Server-side
      The thing to do on the server is to turn bitmap into a string, and then package the other data into JSON and return it to the client.
//Read the picture and turn it into a string     Public StaticStringReadimage(String Imgid) {//byte []data = Imagecontent.getbytes ();File File =NewFile (headimagepath+imgid+". png");Try{FileInputStream InputStream =NewFileInputStream (file);byte[] Bitmaparray =New byte[(int) File.length ()];            Inputstream.read (Bitmaparray); Inputstream.close ();returnBase64.encode (Bitmaparray); }Catch(Exception e) {return ""; }    }//*****************************************    //code piece ..... And the code above is not in the same Java file    //*****************************************    /** * Query a user * * @param userId * PRIMARY key * @return User */    @RequestMapping(Value ="/user/get/{id}")@ResponseBody     PublicJsonobjectGet(@pathvariable("id") String UserId, httpservletresponse response) {Response.setheader ("Access-control-allow-origin","*");        User user = Userdao.getuser (userId); Jsonobject Jsonobject =NewJsonobject (); Jsonobject.put ("User", user);if(User.getuserimage ()! =NULL&&!"". Equals (User.getuserimage ())) {Jsonobject.put ("Userimagecontent", Tool.readimage (User.getuserimage ())); }returnJsonobject; }
    • Client
      This Part I do not post code, because I have a lot of features are encapsulated, to put out a bit of trouble, in short, the picture data has been turned into a string, just need to display, and then turn into bitmap. Please refer to my common class for the implementation of STRING->BITMAP.
Accessibility tools in the 1.4Common class
 /** * image to Byte * @param BM * @return  */     Public Static byte[]bitmap2bytes(Bitmap BM) {Bytearrayoutputstream BAOs =NewBytearrayoutputstream (); Bm.compress (Bitmap.CompressFormat.PNG, -, BAOs);returnBaos.tobytearray (); }/** * Image to String * @param bitmap * @return * *     Public StaticStringbitmap2string(Bitmap Bitmap) {returnBase64.encodetostring (Bitmap2bytes (bitmap), base64.default); }/** * string turns into bitmap * * @param St * *     Public StaticBitmapString2bitmap(String St) {Bitmap Bitmap =NULL;Try{byte[] Bitmaparray;            Bitmaparray = Base64.decode (St, Base64.default); Bitmap = Bitmapfactory.decodebytearray (Bitmaparray,0, bitmaparray.length);returnBitmap }Catch(Exception e) {return NULL; }    }

OK, finally finished, the back to solve the photo, and picture processing problems!

Android Development: Get photo albums, photos, upload servers, read photos from the server

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.