首页 > 解决方案 > 从文本 / html 创建图像 - java-html2image

问题描述

在本地,我有一段代码可以将文本/html 转换为 .jpg 图像。

如果文本包含图像的数据(即 data:xxxx),则数据部分将转换为字节,在磁盘上创建来自这些字节的文件,并将 text/html 更改为引用该文件。

之后,我在磁盘上创建最终图像(文本和图像)。

最后一步使用以下代码完成:

//the below creates a HtmlImageGenerator with the <img src=""/> tag
HtmlImageGenerator htmlImageGenerator = new HtmlImageGenerator();
DOMSource domSource = new DOMSource(doc); //doc is a Document containing text and image
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, streamResult);
htmlImageGenerator.loadHtml(stringWriter.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""));

//sets the dimension and type of the new image
BufferedImage newBufferedImage = new BufferedImage(hig.getBufferedImage().getWidth(), hig.getBufferedImage().getHeight(), BufferedImage.TYPE_INT_RGB);

//create the graphics for the new image
newBufferedImage.createGraphics().drawImage(hig.getBufferedImage(), 0, 0, Color.WHITE, null);

//write the new image on disk
File outputfile = new File(myFilePath + ".jpg");
ImageIO.write(newBufferedImage, "jpg", outputfile);

在我的 windows 机器上这工作正常,但是当我在 Linux 机器上使用相同的代码时,最后一个图像被破坏了。

在我的 Windows 机器上

在linux机器上

知道为什么会这样吗?谢谢

标签: javahtmlimageimage-processing

解决方案


推荐阅读