Android bitmap与Base64的转换

使用json通讯时需要将图片资源转为字符串

/*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /*end*/

base转bitmap

/** 
 * base64转为bitmap 
 * @param base64Data 
 * @return 
 */  
public static Bitmap base64ToBitmap(String base64Data) {  
    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);  
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
}  

转自android bitmap和base64之间的转换

posted @ 2018-06-04 17:14  秦川德利齐  阅读(15389)  评论(1编辑  收藏  举报