場景
專案中有個功能是顯示微信付款碼,為了節省伺服器儲存,將圖片以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;
}
複製程式碼
參考文章: