Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Image to base64 string in java? [duplicate]

Tags:

java

image

base64

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??

like image 649
Setu Kumar Basak Avatar asked Apr 08 '16 05:04

Setu Kumar Basak


People also ask

How can I convert an image into Base64 string using Java?

Convert Image File to Base64 Stringbyte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);

Can we convert image to Base64?

Convert Images to Base64Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!

What is == in Base64?

The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. The size in bytes is divisible by three (bits divisible by 24): All bits are encoded normally.


1 Answers

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"); 
like image 59
Lolo Avatar answered Oct 03 '22 09:10

Lolo