java image 透明_java html转图片,并设置透明背景实现代码

在谷歌上可以找到的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包。

重新执行程序,就得到想要的透明背景图片了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值