How can I convert an image into a Base64 string?

前端 未结 14 1434
离开以前
离开以前 2020-11-22 06:52

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

I need to know how to do it with Android, because I have to add the functionali

14条回答
  •  借酒劲吻你
    2020-11-22 07:24

    You can use the Base64 Android class:

    String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
    

    You'll have to convert your image into a byte array though. Here's an example:

    Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();
    

    * Update *

    If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

    Check this article out for a workaround:

    How to base64 encode decode Android

提交回复
热议问题