项目中有个功能是显示微信付款码,为了节省服务器存储,将图片以Base64的形式存储,客户端接收到后将Base64转换成图片并加载,但是不要存放大图,在网上看到的大多都是使用了一个java库(
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;
),其实Android自带有转换的类(
import android.util.Base64;
)
public static Bitmap stringToBitmap(String string) {
Bitmap bitmap = null;
try {
byte[] bitmapArray = Base64.decode(string.split(",")[1], Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
return bitmap;
需要去掉字符串的data:image/png;base64,
转码并保存成文件
public static void decoderBase64File(String base64Code,String savePath) throws Exception {
//byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
byte[] buffer =Base64.decode(base64Code, Base64.DEFAULT);
FileOutputStream out = new FileOutputStream(savePath);
out.write(buffer);
out.close();
复制代码
转码成bitmap
public 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;
public String bitmaptoString(Bitmap bitmap) {
//将Bitmap转换成字符串
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
复制代码
参考文章:
Android Base64字符串转换成图片
安卓中图片和Base64编码字符集的相互转换
android bitmap和base64之间的转换
安装掘金浏览器插件
多内容聚合浏览、多引擎快捷搜索、多工具便捷提效、多模式随心畅享,你想要的,这里都有!
前往安装