Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert image to base64 with java

I need to convert a image object to a base64 object so I can load it into the tag on my client side.

However I can't seem to figure out how to pull this off. Is there anyone who has a piece of code for this that I could use easily?

This is what I use to turn the external image link into a image object

Image image = null;
URL url = new URL(request.getParameter("hdn_path"));
image = ImageIO.read(url);

not sure if I'm going about this the correct way.

like image 278
NoSixties Avatar asked Feb 01 '15 22:02

NoSixties


People also ask

How to convert an image to Base64 in Java?

FileInputStream class reads byte-oriented data from an image or audio file. By creating a byte array of that file and reading the byte of data from the input stream with the help of read() method from FileInputStream class, we can convert it to the Base64.

How do I change the path to Base64?

String value = Base64. encodeToString(bytes, Base64. DEFAULT);

How is Base64 size calculated?

Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4×6 = 24 bits). This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase).


2 Answers

Using Apache IOUtils and Base64:

byte[] imageBytes = IOUtils.toByteArray(new URL("...")));
String base64 = Base64.getEncoder().encodeToString(imageBytes);
like image 125
Jean Logeart Avatar answered Sep 28 '22 19:09

Jean Logeart


  • write using ImageIO.write().
  • ByteArrayOutputStream wraps the byte array so it can be used as an output stream.
  • convert the byte array to a a base64 string using DatatypeConverter, in core Java since 6, no extra libraries required

Example

ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
DatatypeConverter.printBase64Binary(output.toByteArray());
like image 38
Adam Avatar answered Sep 28 '22 20:09

Adam