Android: Base64 encoding/Decoding of images,
We usually use Base64 encoding/decoding to convert binary data into a visible string format, which is what we often call a large string, which costs 10 yuan a string, ^ _ ^.
The Android. util package of android directly provides a fully functional Base64 class for our use. The following shows how to encode an image using base64.
1. Find the image
public void onEncodeClicked(View view) { //select picture Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, OPEN_PHOTO_FOLDER_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(OPEN_PHOTO_FOLDER_REQUEST_CODE == requestCode && RESULT_OK == resultCode) { //encode the image Uri uri = data.getData(); try { //get the image path String[] projection = {MediaStore.Images.Media.DATA}; CursorLoader cursorLoader = new CursorLoader(this,uri,projection,null,null,null); Cursor cursor = cursorLoader.loadInBackground(); int column_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 it
private void encode(String path) { //decode to bitmap Bitmap bitmap = BitmapFactory.decodeFile(path); Log.d(TAG, "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight()); //convert to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] bytes = baos.toByteArray(); //base64 encode byte[] encode = Base64.encode(bytes,Base64.DEFAULT); String encodeString = new String(encode); mTvShow.setText(encodeString);}
3. Restore the string to an image
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, 90, stream); stream.close(); Log.e("linc","jpg okay!"); } catch (IOException e) { e.printStackTrace(); Log.e("linc","failed: "+e.getMessage()); } }
It should be noted that the encoding speed of an image will be very slow, and it will be even slower if the image is large. After all, mobile phones have limited processing capabilities. However, the decode speed is indeed quite fast, beyond your imagination. Okay, that's simple. It's here today. Good night!