Convert image to base64 using java

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

However, I cannot figure out how to do this. Does anyone have a code for this that I could easily use?

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

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

Not sure if I will do it right.

+6
source share
2 answers

Using Apache IOUtils and Base64

 byte[] imageBytes = IOUtils.toByteArray(new URL("..."))); String base64 = Base64.getEncoder().encodeToString(imageBytes); 
+10
source
  • write using ImageIO.write ().
  • ByteArrayOutputStream wraps an array of bytes, so it can be used as an output stream.
  • convert byte array to base64 string using DatatypeConverter, in Java kernel with 6, no additional libraries required

Example

 ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, "png", output); DatatypeConverter.printBase64Binary(output.toByteArray()); 
+6
source

Source: https://habr.com/ru/post/890709/


All Articles