How to convert an Image to base64 string in java?

125,324

Solution 1

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Solution 2

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

Solution 3

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
Share:
125,324
Setu Kumar Basak
Author by

Setu Kumar Basak

I love to answer questions in SO if I know. Linkedin, Medium

Updated on July 22, 2022

Comments

  • Setu Kumar Basak
    Setu Kumar Basak almost 2 years

    It may be a duplicate but i am facing some problem to convert the image into Base64 for sending it for Http Post. I have tried this code but it gave me wrong encoded string.

     public static void main(String[] args) {
    
               File f =  new File("C:/Users/SETU BASAK/Desktop/a.jpg");
                 String encodstring = encodeFileToBase64Binary(f);
                 System.out.println(encodstring);
           }
    
           private static String encodeFileToBase64Binary(File file){
                String encodedfile = null;
                try {
                    FileInputStream fileInputStreamReader = new FileInputStream(file);
                    byte[] bytes = new byte[(int)file.length()];
                    fileInputStreamReader.read(bytes);
                    encodedfile = Base64.encodeBase64(bytes).toString();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
                return encodedfile;
            }
    

    Output: [B@677327b6

    But i converted this same image into Base64 in many online encoders and they all gave the correct big Base64 string.

    Edit: How is it a duplicate?? The link which is duplicate of mine doesn't give me solution of converting the string what i wanted.

    What am i missing here??