本文介绍了如何获取ImageReader的base64编码内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如何通过ImageReader将图像读入base64编码的字符串中?

How do I read an image into a base64 encoded string by its ImageReader?

这里是使用HtmlUnit的示例源代码.我想获取img的base64字符串:

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());

推荐答案

HtmlUnit的 HtmlImage#getImageReader() 返回 javax.imageio.ImageReader ,它是标准 Java 2D API .您可以获取 BufferedImage 从中可以使用 ImageIO#write() .

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().

Apache Commons Codec Base64OutputStream ,您可以用它装饰OutputStream.

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);

这篇关于如何获取ImageReader的base64编码内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 14:01