3.html转图片
markdown 转图片只是这个插件能力的一个子集,把输入源换成 html,就是本篇的主角:Html2ImageWrapper,它提供了 of / ofDoc / ofMd 三个入口,覆盖 html 片段、完整 html 文档、markdown 产物三种输入姿势
1. 依赖引入
<!-- https://mvnrepository.com/artifact/com.github.liuyueyi.media/markdown-plugin -->
<dependency>
<groupId>com.github.liuyueyi.media</groupId>
<artifactId>markdown-plugin</artifactId>
<version>3.1.0</version>
</dependency>
2. 设计思路
先看看插件内部是怎么把 html 变成图片的,后面讲入口差异时会顺畅很多
整个渲染分两步:
第一步:html 字符串转 Document
html 直接丢给 w3c 标准的 XML 解析器是会挂的(html 太宽容了,标签不闭合、属性不引号都常见),所以这里用的是 nekohtml 的 DOMParser,它在插件初始化时就被创建好了:
private static DOMParser domParser;
static {
domParser = new DOMParser(new HTMLConfiguration());
try {
domParser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
} catch (Exception e) {
throw new RuntimeException("Can't create HtmlParserImpl", e);
}
}
注意 try 语句块里设置的这个 property 不能少,它控制标签名转小写,否则解析出来的样式会错乱
第二步:Document 画到图片上
借助 xhtmlrenderer 的 Graphics2DRenderer,先 layout 拿内容实际尺寸,再 render 到 Graphics2D 画布上:
public static BufferedImage parseImage(HtmlRenderOptions options) {
int width = options.getW();
int height = options.getH() == null ? 1024 : options.getH();
Graphics2DRenderer renderer = new Graphics2DRenderer();
renderer.setDocument(options.getDocument(), options.getDocument().getDocumentURI());
Dimension dimension = new Dimension(width, height);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = GraphicUtil.getG2d(bufferedImage);
if (options.isAutoH() || options.getH() == null) {
// do layout with temp buffer
renderer.layout(graphics2D, new Dimension(width, height));
graphics2D.dispose();
Rectangle size = renderer.getMinimumSize();
final int autoWidth = options.isAutoW() ? (int) size.getWidth() : width;
final int autoHeight = (int) size.getHeight();
bufferedImage = new BufferedImage(autoWidth, autoHeight, BufferedImage.TYPE_INT_RGB);
dimension = new Dimension(autoWidth, autoHeight);
graphics2D = GraphicUtil.getG2d(bufferedImage);
}
renderer.layout(graphics2D, dimension);
renderer.render(graphics2D);
graphics2D.dispose();
return bufferedImage;
}
autoH = true 或 h == null 时走两遍布局:第一遍在临时画布上算出内容的真实宽高,第二遍按真实尺寸正式渲染
3. 三个入口
Html2ImageWrapper 的三个静态入口,对应三种不同的输入形态:
| 入口 | 参数 | 适用场景 |
|---|---|---|
| of(html) | html 片段或字符串 | 手拼的 html、demo.html 这类不带完整结构的片段,可配合 setCss |
| ofDoc(html) | 完整的 html 文档字符串 | 自带 <html><head><style> 的完整文档,css 都写在文档里 |
| ofMd(entity) | MarkdownEntity | markdown 转出来的产物,上一篇已讲 |
三者最终殊途同归:都是拿到一个 Document,然后 build() 装配参数、asXxx() 输出
3.1 of:html 片段 + 独立 css
最直接的使用,直接给一段 html 字符串。下面这个 case 来自测试类 Html2ImgTest,顺带演示了 fontColor 和 fontFamily 的设置:
@Test
public void testHtmp2Img() throws Exception {
String html =
"<html>\n" + "<body>\n" + "\n" + "<span> hello world 爱喝酒</br> 测试测试礼金卡打扫房间连咖啡 </span>\n" + "<hr/>\n" +
"<button> 按钮 </button>\n" + "\n" + "</body>\n" + "</html>";
BufferedImage img =
Html2ImageWrapper.of(html).setFontColor(0xFFFF0000).setAutoW(false).setAutoH(true).setOutType("jpg")
.setFontFamily("monospace").build().asImage();
System.out.println(img);
}
setFontColor(0xFFFF0000) 传的是 int,注意透明度占高两位,红色得写全 0xFFFF0000,写 0xFF0000 颜色就不对了
html 和 css 分离的场景,用 setCss 把样式传进去(css 记得自己包一层 style 标签):
/**
* css 文件和html文件分开的情况
*
* @throws Exception
*/
@Test
public void testParseHtml2Img() throws Exception {
String html = FileReadUtil.readAll("html/demo.html");
String MD_CSS = FileReadUtil.readAll("html/demo.css");
MD_CSS = "<style type=\"text/css\">\n" + MD_CSS + "\n</style>\n";
BufferedImage img =
Html2ImageWrapper.of(html).setCss(MD_CSS).setAutoW(false).setAutoH(false).setOutType("jpg").build()
.asImage();
System.out.println(img);
}
测试资源里的 demo.html 是一段不含 css 的报表内容,demo.css 是配套样式,两者合起来渲染出的就是一张带样式的数据报表图
3.2 ofDoc:完整 html 文档
如果 html 本身就是一份完整的文档(<html><head> 里写好了 <style>),那就不需要 setCss 了,用 ofDoc 直接渲染:
/**
* 完整的html文档, 希望直接进行渲染输出图片,使用 ofDoc 方式
*
* @throws Exception
*/
@Test
public void testFullHtml() throws Exception {
String html = FileReadUtil.readAll("html/full.html");
BufferedImage img = Html2ImageWrapper.ofDoc(html).setOutType("jpg").build().asImage();
System.out.println(img);
}
测试资源 full.html 是一份完整的数据报表通知页面,内部写了十几条 css 规则(字体、卡片阴影、表格配色等),直接渲染输出的图片和浏览器打开效果基本一致
从设计上讲,ofDoc 和 of 的区别在 build() 的分支上:
if (document != null) {
options.setDocument(document);
} else if (css != null) {
html.setCss(css);
options.setDocument(parseDocument(html.toString()));
} else {
// 没有指定css时,默认配置
if (fontColor != null) {
html.addDivStyle("style", "color:" + options.getFontColor() + ";");
}
if (fontFamily != null) {
html.addDivStyle("style", "font-family:" + fontFamily + ";");
}
html.addDivStyle("style", "width:" + w + ";");
html.addWidthCss("img");
html.addWidthCss("code");
options.setDocument(parseDocument(html.toString()));
}
ofDoc走setDocument分支:字符串在setDocument调用时就解析成 Document 了,后面 css、fontColor、fontFamily、w/h 这些配置一概不参与,样式全听 html 文档自己的of走下面两个分支:没 setCss 时,插件会帮你把 fontColor/fontFamily/宽度限制拼进 html;setCss 了就完全以你的 css 为准
所以选入口的经验是:html 自带完整样式用 ofDoc,样式靠外部给的用 of + setCss,想省事用默认样式的用 of + setFont/setFontColor
3.3 输出方式
build() 拿到 Html2ImageWrapper 之后,有三种输出姿势:
// 输出 BufferedImage,拿去继续加工(加水印、拼图等)
BufferedImage image = wrapper.asImage();
// 直接保存到本地文件,父目录不存在会自动创建
boolean ok = wrapper.asFile("/tmp/out/report.jpg");
// 输出 base64 编码的字符串,适合直接塞给前端 <img> 标签
String base64 = wrapper.asString();
asFile 内部就是 ImageIO.write(bufferedImage, options.getOutType(), file),所以保存的格式跟 setOutType 是一回事;asString 内部走的是 Base64Util.encode(img, options.getOutType())
4. 常见坑
4.1 ofDoc 之后 set 样式参数不生效
上面 build() 的分支逻辑已经说明白了:ofDoc 时 Builder 上的 css、fontColor、fontFamily 全都被忽略。如果你的完整 html 文档里没写样式,渲染出来就是裸的黑白文本,别以为是参数没传对——要么改用 of 入口,要么把样式写进 html 里
4.2 css 和其他样式参数是二选一的
of 入口下,setCss 一旦调用,fontColor/fontFamily/宽度限制的默认拼装逻辑就跳过了。想要「自定义 css + 指定字体」的效果,直接把 font-family 写在 css 里最省事
4.3 中文乱码
和上一篇 md 转图片一样的问题:linux 服务器 JRE 缺中文字体时,渲染出来的中文是方框。解决思路也一样,往 JRE 的字体目录丢一个中文字体文件(如 simsun.ttf)重启即可;开发阶段在 win/mac 上通常感知不到,上线前务必检查
4.4 内容被裁掉或大片留白
固定 h 且 autoH = false 时,内容超过 h 会被裁掉,不足则留白。对长度不可控的内容(报表、文章),推荐 setH 不传或 setAutoH(true),让插件自适应;需要严格固定尺寸(如生成封面图)时再固定宽高,并自己控制内容的量
5. 小结
本篇把 Html2ImageWrapper 的三个入口讲完了,加上上一篇的 ofMd,markdown-plugin 对外的能力就齐了:给 markdown 或 html,还你一张图。如果 xhtmlrenderer 这套纯 Java 的渲染满足不了需求(比如需要 js 执行的现代前端页面),可以再看看同项目里基于 PhantomJs 的 phantom 插件,那个是另一个路数
项目地址:
- https://github.com/liuyueyi/quick-media
QuickMedia目标是创建一个专注图文,音视频,二维码处理的开源项目