Android: Encode & Decode base64

前端 未结 2 2011
花落未央
花落未央 2021-01-17 03:54

How to encode and decode any image from base64 format.

I donno anything about base64, just now I came to know that it saves image in String format. Please explain ab

2条回答
  •  臣服心动
    2021-01-17 04:41

    Base64 allows you to represent binary data in ASCII format, You can use it for send/receive images to an endpoint

    To encode/decode check this two methods:

    public static String getBase64(Bitmap bitmap)
    {
        try{
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
    
            return Base64.encodeToString(byteArray, Base64.NO_WRAP);
        }
        catch(Exception e)
        {
            return null;
        }
    }
    
    public static Bitmap getBitmap(String base64){
        byte[] decodedString = Base64.decode(base64, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }
    

提交回复
热议问题