HTML转图片-----java

本文介绍两种将HTML内容转换为图片的方法:使用html2image库直接转换内联HTML文本,以及利用Cobra渲染复杂网页并截图。前者适用于简单HTML文档,后者更适合完整网页快照。

###偶然有一个HTML转换为图片的需求,因此在网上搜遍了找到以下实现方式。


#1. html2image

html2image

<!-- lang: java -->
String htmlTxt = "<h1>开源中国社区</h1><h3>Header 3</h3><blockquote><p>This is a blockquote.</p><p>This is the second paragraph in the blockquote.</p><h2>This is an H2 in a blockquote</h2></blockquote>";
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(htmlTxt);
imageGenerator.saveAsImage("html.png");

#2. Cobra

Cobra

<!-- lang: java -->
JFrame window = new JFrame();  
HtmlPanel panel = new HtmlPanel();  
window.getContentPane().add(panel);  
window.setSize(600, 400);  
window.setVisible(true);  
new SimpleHtmlRendererContext(panel, new SimpleUserAgentContext()).navigate("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95.html");  
BufferedImage image = new BufferedImage(panel.getWidth(),  
panel.getHeight(), BufferedImage.TYPE_INT_ARGB);  
SwingUtilities.paintComponent(image.createGraphics(), panel,  new JPanel(), 0, 0, image.getWidth(), image.getHeight());  
ImageIO.write((RenderedImage) image, "png", new File("html.png"));  

转载于:https://my.oschina.net/mercury5/blog/159575

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值