#####一、第一种保存本地的方式
fileBase64 = 服务端返回base64
- 过滤信息
//过滤掉base64中一些头部的信息
if (fileBase64.contains("base64,")) {
fileBase64 = fileBase64.substring(fileBase64.indexOf("base64,") + 6);
}
复制代码
byte[] decode = Base64.decode(fileBase64,Base64.DEFAULT);
String path = "sd卡路径";
createFileWithByte(decode,path)
/**
* 根据byte数组生成文件
*
* @param bytes 生成文件用到的byte数组
*/
public static void createFileWithByte(byte[] bytes, String path) {
// TODO Auto-generated method stub
/**
* 创建File对象,其中包含文件所在的目录以及文件的命名
*/
File file = new File(path);
// 创建FileOutputStream对象
FileOutputStream outputStream = null;
// 创建BufferedOutputStream对象
BufferedOutputStream bufferedOutputStream = null;
try {
// 如果文件存在则删除
if (file.exists()) {
file.delete();
}
// 在文件系统中根据路径创建一个新的空文件
file.createNewFile();
// 获取FileOutputStream对象
outputStream = new FileOutputStream(file);
// 获取BufferedOutputStream对象
bufferedOutputStream = new BufferedOutputStream(outputStream);
// 往文件所在的缓冲输出流中写byte数据
bufferedOutputStream.write(bytes);
// 刷出缓冲输出流,该步很关键,要是不执行flush()方法,那么文件的内容是空的。
bufferedOutputStream.flush();
} catch (Exception e) {
// 打印异常信息
e.printStackTrace();
} finally {
// 关闭创建的流对象
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
} false;
}
}
复制代码
#####二、第二种base64转成Bitmap的方式
//直接转成Bitmap,然后可以设置用了
Bitmap bitmap = stringtoBitmap(fileBase64);
public static Bitmap stringtoBitmap(String string) {
//将字符串转换成Bitmap类型
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
复制代码