Android實戰技巧之三十七:圖片的Base64編解碼,
通常用Base64這種編解碼方式將位元據轉換成可見的字串格式,就是我們常說的大串,10塊錢一串的那種,^_^。
Android的android.util包下直接提供了一個功能十分完備的Base64類供我們使用,下面就示範一下如何將一張圖片進行Base64的編解碼。
1.找到那張圖片
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.將圖片轉換成bitmap並編碼
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.將大串還原成圖片
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()); } }
需要注意的是,一張圖片的編碼速度會很慢,如果圖片很大就更慢了。畢竟手機的處理能力有限。不過decode的速度確實相當的快,超出你的想象。好了,就是這樣簡單,今天就到這裡了,晚安!