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.
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.
String value = Base64. encodeToString(bytes, Base64. DEFAULT);
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).
Using Apache IOUtils
and Base64
:
byte[] imageBytes = IOUtils.toByteArray(new URL("...")));
String base64 = Base64.getEncoder().encodeToString(imageBytes);
Example
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
DatatypeConverter.printBase64Binary(output.toByteArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With