设为首页 加入收藏

TOP

Java 实现HTML 页面转成image 图片
2014-11-24 11:59:56 来源: 作者: 【 】 浏览:36
Tags:Java 实现 HTML 页面 image 图片
前言
在java 中把HTML转化成图档,思路基本上是现在 AWT or Swing 的Panel上显示网页,在把Panel输出为 image 文件。
java 本身的API有提供相关的结果,但是直接产生的效果不是很好,所以有出现一些 library.
Java Core API
[java]
public class HtmlToImage {
protected static void generateOutput() throws Exception {
//load the webpage into the editor
//JEditorPane ed = new JEditorPane(new URL("http://www.google.com"));
JEditorPane ed = new JEditorPane(new URL("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95. html"));
ed.setSize(200,200);
//create a new image
BufferedImage image = new BufferedImage(ed.getWidth(), ed.getHeight(),
BufferedImage.TYPE_INT_ARGB);
//paint the editor onto the image
SwingUtilities.paintComponent(image.createGraphics(),
ed,
new JPanel(),
0, 0, image.getWidth(), image.getHeight());
//save the image to file
ImageIO.write((RenderedImage)image, "png", new File("html.png"));
}
public static void main(String[] args) {
try {
generateOutput();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java-html2image
开源, 使用上很简洁。API Doc 和source code 都有。
[java]
import gui.ava.html.image.generator.HtmlImageGenerator;
public class Html2ImageTest {
public static void main(String[] args) {
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
// imageGenerator
// .loadHtml("Hello World! Please goto Google.");
//imageGenerator.loadUrl("http://mtkplmap2:7001/esdm_web");
imageGenerator.loadUrl("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95.html");
imageGenerator.saveAsImage("hello-world.png");
imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
}
}
Cobra
免费,开源
[java]
public class CobraTest {
public static void main(String[] args) throws Exception {
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);
// paint the editor onto the image
SwingUtilities.paintComponent(image.createGraphics(), panel,
new JPanel(), 0, 0, image.getWidth(), image.getHeight());
// save the image to file
ImageIO.write((RenderedImage) image, "png", new File("html.png"));
}
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇java函数参数类型后添加三点的用法 下一篇设计模式笔记---简单工厂模式(201..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis压力测试实战 - (2025-12-27 09:20:24)
·高并发一上来,微服 (2025-12-27 09:20:21)
·Redis 高可用架构深 (2025-12-27 09:20:18)
·Linux 系统监控 的完 (2025-12-27 08:52:29)
·一口气总结,25 个 L (2025-12-27 08:52:27)