我是靠谱客的博主 默默雪碧,这篇文章主要介绍java 将html转为图片,然后转为base64,现在分享给大家,希望可以做个参考。

将HTML页面转为图片,找了很多方法,发现CSSBox对前端css支持性最好。在解码base64的时候,会出现中文乱码的问题,删除空格和换行即可

采用CSSBox(http://cssbox.sourceforge.net/) 

复制代码
1
2
3
4
5
<dependency> <groupId>net.sf.cssbox</groupId> <artifactId>cssbox</artifactId> <version>4.12</version> </dependency>

HTML转图片,再转base64

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
ImageRenderer render = new ImageRenderer(); String url = "http://127.0.0.1:8080/api/receiptPage"; File file; InputStream inputStream = null; byte[] data = null; try { //创建一个临时文件 file = File.createTempFile("temp", ".png"); //将html转为png FileOutputStream out = new FileOutputStream(file); render.renderURL(url, out, ImageRenderer.Type.PNG); //字节流读取png inputStream = new FileInputStream(file); data = new byte[inputStream.available()]; inputStream.read(data); out.close(); inputStream.close(); file.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); //删除所有空格,换行,解决base解码出现中文乱码 return encoder.encode(data).replaceAll("n", "").replaceAll("r", "");

解码base64

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static boolean generateImage(String imgStr) { if(imgStr == null){ return false; } BASE64Decoder decoder = new BASE64Decoder(); try{ byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0;i<b.length;++i){ if(b[i]<0){ b[i]+=256; } } OutputStream out = new FileOutputStream(new File("d:/html.png")); out.write(b); out.flush(); out.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } }

 

最后

以上就是默默雪碧最近收集整理的关于java 将html转为图片,然后转为base64的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部