-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
66 lines (54 loc) · 1.29 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
/**
* Expose `thumb()`.
*/
module.exports = thumb;
/**
* Scale `img` to fit within `width` / `height`
* and and invoke `fn(err, img)`.
*
* @param {String|Image} img or data uri
* @param {Number} width
* @param {Number} height
* @param {Function} fn
* @api public
*/
function thumb(img, width, height, fn, quality) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
if ('string' == typeof img) {
fromURI(img, resize);
} else {
resize(null, img);
}
function resize(err, img) {
if (err) return fn(err);
var ratio = img.width / width > img.height / height
? img.width / width
: img.height / height;
if (ratio > 1) {
width = Math.ceil(img.width / ratio);
height = Math.ceil(img.height / ratio);
} else {
width = img.width;
height = img.height;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
fromURI(canvas.toDataURL('image/jpeg', quality || .9), fn);
}
}
/**
* Return `Image` from data uri `str`
* and invoke `fn(err, img)`.
*
* @param {String} str
* @param {Function} fn
* @api private
*/
function fromURI(str, fn) {
var img = new Image
img.onerror = fn;
img.onload = function(e){ fn(null, img, str) };
img.src = str;
}