How do I read an image into a base64 encoded string by its ImageReader?
Here’s example source code using HtmlUnit. I want to get the base64 String of img:
WebClient wc = new WebClient();
wc.setThrowExceptionOnFailingStatusCode(false);
wc.setThrowExceptionOnScriptError(false);
HtmlPage p = wc.getPage("http://flickr.com");
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
System.out.println(img.getImageReader().getFormatName());
The HtmlUnit’s
HtmlImage#getImageReader()returnsjavax.imageio.ImageReaderwhich is part of standard Java 2D API. You can get anBufferedImageout of it which you in turn can write to anOutputStreamof any flavor usingImageIO#write().The Apache Commons Codec has a
Base64OutputStreamwhich you can just decorate yourOutputStreamwith.Or if you want to write it to file directly: