Image to Base64 String example

In this example, we will be learning how to implement conversion from image to Base64 String image. In the previous post, we have covered the case when we needed to convert Base64 String to Image. In short, we are going to take one image from our image gallery, convert it into a Base64 String, and display that string on screen, alongside the image that we have selected.

This example is a followup post from Base64 String to Image example and Select image from gallery and display it on screen. example and we will continue where we have left from the post above.

 

First we will add new text element to our layout (Constraint Layout) for displaying the Base64 String image:

In here we have an text holder and an overlay for UI purposes only.

Because in the previous examples, the image in onActivityForResult() is converted in to Bitmap object, the apropriate method is created that receives Bitmap object as a parameter and returns byte array to be used later on the conversion to Base64 String Image:

In here not only we get the Byte array output stream, baos, but also we add format to our image and the compression, or quality, of the image. In CompressFormat we can add JPEG, PNG and WEBP format. For compression quality the scale is from 0 to 100, 0 being the lowest quality and 100 the highest. Then the conversion to Base64 String Image can begin:

Here we use our previously created imageToByteArray() method, passing the bitmap that we have created from the selected picture from our gallery, as an argument. Then newly created imageBytes byte array, is passed as an argument in Base64.encodeToString method. This method requires byte[] and int flag which flag can be crafted to our needs for playing around with the text.

 

 

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *