forked from juliangruber/capture-screenshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
118 lines (97 loc) · 2.11 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var exec = require('child_process').exec;
module.exports = Screenshot;
/**
* Create screenshot object.
*
* @param {String} url
* @param {Object=} opts
* @return {Screenshot}
*/
function Screenshot(url, opts) {
if (!(this instanceof Screenshot)) return new Screenshot(url, opts);
this.url = url;
this.width(1024);
this.height(768);
this.timeout(0);
this.format('png');
Object.keys(opts || {}).forEach(function (key) {
if (typeof this[key] == 'function') this[key](opts[key]);
}.bind(this));
}
/**
* Set `width`.
*
* @param {Number} width
* @return {Screenshot}
*/
Screenshot.prototype.width = function(width) {
this._width = width;
return this;
};
/**
* Set `height`.
*
* @param {Number} height
* @return {Screenshot}
*/
Screenshot.prototype.height = function(height) {
this._height = height;
return this;
};
/**
* Set `timeout` for PhantomJS.
*
* @param {Number} timeout
* @return {Screenshot}
* @todo Find more flexible mechanism
*/
Screenshot.prototype.timeout = function(timeout) {
this._timeout = timeout;
return this;
};
/**
* Set output image format.
*
* Supported formats:
* - jpg, jpeg
* - png
* - gif
*
* @param {String} format
* @throws {TypeError}
* @return {Screenshot}
*/
Screenshot.prototype.format = function(format) {
format = format.toUpperCase();
if (format == 'JPEG') format = 'JPG';
if (['JPG', 'PNG', 'GIF'].indexOf(format) == -1)
throw new TypeError('unknown format');
this._format = format;
return this;
};
/**
* Capture the screenshot and call `fn` with `err` and `img`.
*
* @param {Function} fn
*/
Screenshot.prototype.capture = function(fn) {
if (!fn) {
var self = this;
return function(fn) {
self.capture(fn);
}
}
var path = __dirname + '/script/render.js';
if(/^win/.test(process.platform))
path = '"'+path+'"';
var args = [
path, this.url,
this._width, this._height, this._timeout, this._format
];
var opts = {
maxBuffer: Infinity
};
exec('phantomjs ' + args.join(' '), opts, function (err, stdout) {
fn(err, stdout && new Buffer(stdout, 'base64'));
});
};