Usually use Base64 this codec way to convert binary data into a visible string format, which is what we often say, 10 dollars a string of the kind, ^_^.
Android Android.util package directly provides a fully functional Base64 class for us to use, the following shows how to make a picture of Base64 codec.
1. Find the picture
Public void onencodeclicked(View view) {//select PictureIntent Intent =NewIntent (); Intent.settype ("image/*"); Intent.setaction (intent.action_get_content); Startactivityforresult (Intent, Open_photo_folder_request_code); }@Override protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {Super. Onactivityresult (Requestcode, ResultCode, data);if(Open_photo_folder_request_code = = Requestcode && RESULT_OK = = ResultCode) {//encode the imageUri uri = Data.getdata ();Try{//get the image pathstring[] projection = {MediaStore.Images.Media.DATA}; Cursorloader Cursorloader =NewCursorloader ( This, Uri,projection,NULL,NULL,NULL); cursor cursor = Cursorloader.loadinbackground ();intColumn_index = Cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA); Cursor.movetofirst (); String path = cursor.getstring (Column_index); LOG.D (TAG,"Real Path:"+path); Encode (path); }Catch(Exception ex) {LOG.E (TAG,"failed."+ ex.getmessage ()); } } }
2. Convert the image to bitmap and encode
Private void encode(String Path) {//decode to bitmapBitmap Bitmap = bitmapfactory.decodefile (path); LOG.D (TAG,"Bitmap width:"+ bitmap.getwidth () +"Height:"+ bitmap.getheight ());//convert to byte arrayBytearrayoutputstream BAOs =NewBytearrayoutputstream (); Bitmap.compress (Bitmap.CompressFormat.PNG, -, BAOs);byte[] bytes = Baos.tobytearray ();//base64 encode byte[] encode = Base64.encode (Bytes,base64.default); String encodestring =NewString (encode); Mtvshow.settext (encodestring);}
3. Restore a large string into a picture
public void ondecodeclicked (view view) {byte[] decode = Base64. Decode(Mtvshow. GetText(). toString(), Base64. DEFAULT);Bitmap Bitmap = bitmapfactory. Decodebytearray(Decode,0, decode. Length);Save to image on SDcard savebitmap (bitmap);private void Savebitmap (Bitmap Bitmap) {try {String path = Environment. getExternalStorageDirectory(). GetPath() +"/decodeimage.jpg";Log. D("Linc","Path is"+path);OutputStream stream = new FileOutputStream (path);Bitmap. Compress(Bitmap. Compressformat. JPEG, -, stream);Stream. Close();Log. E("Linc","jpg okay!");} catch (IOException e) {E. Printstacktrace();Log. E("Linc","failed:"+e. GetMessage());} }
It is important to note that the encoding of a picture is very slow, and if the picture is large, it will be slower. After all, mobile phone processing capacity is limited. But the speed of decode is indeed quite fast, beyond your imagination. All right, that's it, it's easy, it's here today, good night!
Android Combat 37: Base64 codec for images