Requirements: In the Android mobile and the server for data interaction, sometimes need to upload, download files. It is more convenient if all of the arguments become strings.
Principle: Base64 simply encodes the byte[] array, and then decodes the process, the document content cannot be read directly. In some ways, "encryption" has been done. After testing a picture into a string it will probably be less than 1 and a half of the size.
In fact, I personally feel that not using Base64 myself through GetByte () and new String () should also be no problem. The encoded format can be as long as the data is not lost.
For class objects, we can also do this through ObjectOutputStream and ObjectInputStream. This can be transformed into a string to be transmitted in a way.
Here is a demo, how to turn a picture into a string, and turn the string into a picture.
PackageCom.itheima.base64demo_8;ImportJava.io.ByteArrayOutputStream;ImportJava.io.ObjectOutputStream;ImportJava.io.OutputStream;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.Bitmap.CompressFormat;Importandroid.graphics.BitmapFactory;Importandroid.graphics.drawable.Drawable;Importandroid.util.Base64;ImportAndroid.view.Menu;ImportAndroid.widget.ImageView; Public classMainactivityextendsActivity {PrivateImageView mIv; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); MIv=(ImageView) Findviewbyid (R.ID.IV); //1. Get a picture from drawable-hdpiBitmap Sourcebitmap =Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.BBB); //2. Convert to byte[]Bytearrayoutputstream out =NewBytearrayoutputstream (); Sourcebitmap.compress (Compressformat.jpeg,100, out); byte[] Sourcebitmapbytearr =Out.tobytearray (); //3.base64-->stringString bitmapstring =base64.encodetostring (Sourcebitmapbytearr, Base64.default); System.out.println ("Bitmapstring:" +bitmapstring); //4.base64-->string-->byte[] byte[] Bitmapdecodebytearr =Base64.decode (bitmapstring, Base64.default); //5.byte[]-->bitmapBitmap Bitmap = Bitmapfactory.decodebytearray (Bitmapdecodebytearr, 0, bitmapdecodebytearr.length); //6.bitmap is set to MIV SRC, verifying that this can be passedMiv.setimagebitmap (bitmap); }}
Overall, there is no difficulty.
BASE64 technology: turning objects into strings