这篇文章主要讲解了Java利用Phantomjs实现生成图片的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

今天,给大家分享一个Java后端利用Phantomjs实现生成图片的功能,同学们使用的时候,可以参考下!
PhantomJS简介
首先,什么是PhantomJS?
根据官网介绍:
PhantomJS is a command-line tool. -- 其实就是一个命令行工具。
PhantomJS的下载地址:
Windows:phantomjs-2.1.1-windows.zip
Linux:phantomjs-2.1.1-linux-x86_64.tar.bz2;phantomjs-2.1.1-linux-i686.tar.bz2
MacOS:phantomjs-2.1.1-macosx.zip
下载下来后,我们看到bin目录下就是可执行文件phantomjs.exe,我们可以将它配置到环境变量中,方便命令使用!
还有一个examples目录,它下面是很多js样例,关于这些样例作用,参考官网解释,给大家做个简单翻译:
1. Basic examples
2. Rendering/rasterization
3. Page automation
4. Network
5. Testing
6. Browser
今天,我们根据网页URL生成图片,使用的就是rasterize.js:将网页光栅化为图像或PDF。
了解rasterize.js
我们来看一下rasterize.js的内容(源文件对size的处理有错误,这里已修正!):
"use strict";
var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px');
console.log(' "800px*600px" window, clipped to 800x600');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 800, height: 200 };
if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
size = system.args[3].split('*');
page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }
: { format: system.args[3], orientation: 'portrait', margin: '1cm' };
} else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
size = system.args[3].split('*');
if (size.length === 2) {
var pageWidth = parseInt(size[0].substr(0,size[0].indexOf("px")), 10);
var pageHeight = parseInt(size[1].substr(0,size[1].indexOf("px")), 10);
page.viewportSize = { width: pageWidth, height: pageHeight };
page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
} else {
var pageWidth = parseInt(system.args[3].substr(0,system.args[3].indexOf("px")), 10);
var pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
page.viewportSize = { width: pageWidth, height: pageHeight };
}
}
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}