參考:java
Convert base64 image data to an image file(.png) and save it to Local file systemandroid
String base64Img = ""; // 若包含"data:image/jpeg;base64,"前綴,只取後邊的部分 if (base64Img.contains(",")) { String[] base64ImgArray = base64Img.split(","); if (base64ImgArray.length == 2) { base64Img = base64ImgArray[1]; } } // 解碼 try { byte[] decodedString = Base64.decode(base64Img, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); if (mBitmapCreateListener != null) { mBitmapCreateListener.onBitmapCreate(decodedByte); } } catch (Exception e) { e.printStackTrace(); // 回調生成圖片失敗 if (mBitmapCreateListener != null) { mBitmapCreateListener.onBitmapCreate(null); } }
FileOutputStream fos = null; try { if (base64ImageData != null) { fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE); byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT); fos.write(decodedString); fos.flush(); fos.close(); } } catch (Exception e) { } finally { if (fos != null) { fos = null; } }