How to convert image to base64 string in java?

It may be a duplicate, but I ran into some problem to convert the image to Base64 to send it to Http Post . I tried this code, but it gave me the 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 the same image in Base64 to many online encoders, and all of them gave the correct large Base64 string.

Edit: How is this a duplicate? The link, which is a duplicate of mine, does not give me the decision to convert the string that I wanted.

What am I missing here?

+8
java image base64
source share
3 answers

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

Instead, you should do:

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

I think you might need:

 String encodedFile = Base64.getEncoder().encodeToString(bytes); 
+4
source share

it did it for me. You can change the output format parameters to Base64.Default in general.

 // 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); 
+1
source share

All Articles