动态图片生成html页面上,(一)使用phantomjs将动态HTML页面生成图片

因为工作需要,笔者需要将一个动态的HTML5页面生成图片,并将图片发送给用户。

其中难点在于怎样将动态H5生成图片

笔者翻阅资料后,决定使用phantomjs这个插件,关于这个插件的安装,非常简单,笔者不再赘述。

安装好插件后就是怎样使用这个插件了。

下面附上笔者的调用

private voidexePhantomjs(String url,String filename){

String BLANK= " ";

Process process= null;try{

process=Runtime.getRuntime().exec(

phantomjs+ BLANK //你的phantomjs.exe路径

+ calendarjs + BLANK //就是上文中那段javascript脚本的存放路径

+ url + BLANK //你的目标url地址

+ filePath+filename+".jpg");

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

logger.info(phantomjs+ BLANK+calendarjs + BLANK+url + BLANK+filePath+filename+".jpg");

InputStream inputStream=process.getInputStream();

BufferedReader reader= new BufferedReader(newInputStreamReader(inputStream));

String tmp= "";try{while ((tmp = reader.readLine()) != null) {if (process != null) {

process.destroy();

process= null;

}

}

inputStream.close();

reader.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("渲染成功...");

}

这里相当是JAVA直接调用第三方插件。需要传入四个参数

1,phantomjs的路径

2,执行脚本

3,动态H5的地址,可以使用百度地址进行测试,笔者在开发时使用了自己后台的H5页面

4,图片生成路径

接下来附上笔者的脚本

var page = require('webpage').create(), system = require('system'), address, output, size;if (system.args.length < 3 || system.args.length > 5) {

phantom.exit(1);

}else{

address= system.args[1];

output= system.args[2];//定义宽高

page.viewportSize ={

width :1242,

height :10000};

page.open(address, function(status) {var bb =page.evaluate(function() {return document.getElementsByTagName('html')[0].getBoundingClientRect();

});var cc =page.evaluate(function() {returndocument.documentElement;

});

page.clipRect={

top : bb.top,

left : bb.left,

width : bb.width,

height : cc.scrollHeight

};

window.setTimeout(function() {

page.render(output);

page.close();

console.log('success...');//for (var item in cc){//if('scrollHeight'==item){//console.log(item,cc[item])//}//}

console.log('height',cc.scrollHeight)

phantom.exit(1);

},1000);

});

}

整个过程比较简单,但是从技术选型,到开发,调试也历时一个星期。

最后附上笔者生成的图片

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值