Java 实现HTML 页面转成image 图片

前言

在java 中把HTML转化成图档,思路基本上是现在 AWT or Swing 的Panel上显示网页,在把Panel输出为 image 文件。

java 本身的API有提供相关的结果,但是直接产生的效果不是很好,所以有出现一些 library.

Java Core API

public class HtmlToImage {protected static void generateOutput() throws Exception {//load the webpage into the editor//JEditorPane ed = new JEditorPane(new URL(""));JEditorPane ed = new JEditorPane(new URL(""));ed.setSize(200,200);//create a new imageBufferedImage image = new BufferedImage(ed.getWidth(), ed.getHeight(),BufferedImage.TYPE_INT_ARGB);//paint the editor onto the imageSwingUtilities.paintComponent(image.createGraphics(),ed,new JPanel(),0, 0, image.getWidth(), image.getHeight());//save the image to fileImageIO.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 都有。

import gui.ava.html.image.generator.HtmlImageGenerator;public class Html2ImageTest {public static void main(String[] args) {HtmlImageGenerator imageGenerator = new HtmlImageGenerator();//imageGenerator//.loadHtml("<b>Hello World!</b> Please goto <a title=\&;Goto Google\&; href=\&;\&;>Google</a>.");//imageGenerator.loadUrl(":7001/esdm_web"); imageGenerator.loadUrl(""); imageGenerator.saveAsImage("hello-world.png");imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");}}

Cobra免费,开源

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("");BufferedImage image = new BufferedImage(panel.getWidth(),panel.getHeight(), BufferedImage.TYPE_INT_ARGB);// paint the editor onto the imageSwingUtilities.paintComponent(image.createGraphics(), panel,new JPanel(), 0, 0, image.getWidth(), image.getHeight());// save the image to fileImageIO.write((RenderedImage) image, "png", new File("html.png"));}}

WebRenderer

收费的。

下载包里有包含很多例子,, 效果类似在swing 中使用browser的功能

总结不管是哪一种,多于样式复杂的页面,

产生的效果都不尽如人意。。。

因为冲动会做下让自己无法挽回的事情。

Java 实现HTML 页面转成image 图片

相关文章:

你感兴趣的文章:

标签云: