android 中将 "base64图片" 解码为".png"图片
参考:
方法一
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;
}
}