【发布时间】:2011-05-25 04:20:18
【问题描述】:
如何在不创建的情况下轻松地将 html 转换为图像,然后转换为字节数组
谢谢
【问题讨论】:
-
像呈现的 html 页面的“屏幕截图”?
-
不,我创建了html,我需要通过传真发送没有图片源的图片,所以我想把它转换成图片然后发送图片
标签: java html image renderer layout-engine
如何在不创建的情况下轻松地将 html 转换为图像,然后转换为字节数组
谢谢
【问题讨论】:
标签: java html image renderer layout-engine
这很重要,因为渲染 HTML 页面可能非常复杂:您需要评估文本、图像、CSS,甚至可能是 JavaScript。
我不知道答案,但我确实有一些东西可以帮助你:iText(一个 PDF 写作库)的代码,用于将 HTML 页面转换为 PDF 文件。
public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
final ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(xhtmlUrl);
renderer.layout();
renderer.createPDF(reportPdfStream);
reportPdfStream.close();
}
【讨论】:
如果您没有任何复杂的 html,您可以使用普通的 JLabel 来呈现它。下面的代码将产生这个图像:
<html>
<h1>:)</h1>
Hello World!<br>
<img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
public static void main(String... args) throws IOException {
String html = "<html>" +
"<h1>:)</h1>" +
"Hello World!<br>" +
"<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
"</html>";
JLabel label = new JLabel(html);
label.setSize(200, 120);
BufferedImage image = new BufferedImage(
label.getWidth(), label.getHeight(),
BufferedImage.TYPE_INT_ARGB);
{
// paint the html to an image
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
label.paint(g);
g.dispose();
}
// get the byte array of the image (as jpeg)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
....
}
如果您只想将其写入文件:
ImageIO.write(image, "png", new File("test.png"));
【讨论】:
ImageIO.write 之类的操作。如果没有图像,就无法神奇地构造字节数组。
BufferedImage 转换为byte[] 时,您需要知道应如何将数据打包到数组中。格式有很多bmp、jpg、gif等
【讨论】:
在上面的代码中使用内存中的ByteArrayStream 而不是FileOutputStream 怎么样?那将是一个字节数组,至少......
【讨论】: