问题
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());
回答1:
The HtmlUnit's HtmlImage#getImageReader() returns javax.imageio.ImageReader which is part of standard Java 2D API. You can get an BufferedImage out of it which you in turn can write to an OutputStream
of any flavor using ImageIO#write().
The Apache Commons Codec has a Base64OutputStream which you can just decorate your OutputStream
with.
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
ImageReader imageReader = img.getImageReader();
BufferedImage bufferedImage = imageReader.read(0);
String formatName = imageReader.getFormatName();
ByteArrayOutputStream byteaOutput = new ByteArrayOutputStream();
Base64OutputStream base64Output = new base64OutputStream(byteaOutput);
ImageIO.write(bufferedImage, formatName, base64output);
String base64 = new String(byteaOutput.toByteArray());
Or if you want to write it to file directly:
// ...
FileOutputStream fileOutput = new FileOutputStream("/base64.txt");
Base64OutputStream base64Output = new base64OutputStream(fileOutput);
ImageIO.write(bufferedImage, formatName, base64output);
回答2:
I'm not quite sure what exactly you want.
But what about creating your own Reader (see javax.imageio.stream.ImageInputStreamImpl), containing the Base64-stuff? Maybe this external free Base64Encoder can help you out.
Something that could be used like this in the end?
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);
MyBase64EncodingReader reader = new MyBase64EncodingReader(img);
System.out.println(reader.toString());
回答3:
You could use one of the encodeBase64 methods
from apache commons codec.
and create a string from the resulting byte array using the String(bytes[]) constructor.
来源:https://stackoverflow.com/questions/3068543/how-to-get-base64-encoded-contents-for-an-imagereader