在谷歌上可以找到的java库html2image,直接可将html内容转为image保存起来
http://java-html2image.googlecode.com/files/html2image-0.9.jar
简单的例子如下
import gui.ava.html.image.generator.HtmlImageGenerator;
public class txt2img {
public static void main(String[] args) throws Exception {
String text = args[0];
String filename = args[1];
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(text);
imageGenerator.getBufferedImage();
imageGenerator.saveAsImage(filename);
}
}
不过生成图片后发现,图片背景是白色的,但我只需要内容,要透明的背景。
查了文档,没有说到这个库能设置背景的,网上进行搜索也没有相关内容,于是只好找来源码自己研究。
发现其中类HtmlImageGenerator使用了JEditorPane来处理html,嘿嘿,通过查找JEditorPane的资料可以修改背景。
修改类HtmlImageGenerator中的createJEditorPane函数,如下
protected JEditorPane createJEditorPane() {
final JEditorPane editorPane = new JEditorPane();
editorPane.setBackground(new Color(0,0,0,0));//设置背景透明
editorPane.setSize(getDefaultSize());
editorPane.setEditable(false);
final SynchronousHTMLEditorKit kit = new SynchronousHTMLEditorKit();
editorPane.setEditorKitForContentType("text/html", kit);
editorPane.setContentType("text/html");
editorPane.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("page")) {
onDocumentLoad();
}
}
});
return editorPane;
}
改后再重新编译成jar包。
重新执行程序,就得到想要的透明背景图片了。