forked from pioug/colorsuite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom-pixels.js
107 lines (102 loc) · 2.53 KB
/
dom-pixels.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
"use strict";
var path = require("path");
var ndarray = require("ndarray");
var GifReader = require("omggif").GifReader;
var pack = require("ndarray-pack");
var through = require("through");
function defaultImage(url, cb) {
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
var pixels = context.getImageData(0, 0, img.width, img.height);
cb(
null,
ndarray(
new Uint8Array(pixels.data),
[img.width, img.height, 4],
[4, 4 * img.width, 1],
0
)
);
};
img.onerror = function (err) {
cb(err);
};
img.src = url;
}
//Animated gif loading
function handleGif(data, cb) {
var reader;
try {
reader = new GifReader(data);
} catch (err) {
cb(err);
return;
}
if (reader.numFrames() > 0) {
var nshape = [reader.numFrames(), reader.height, reader.width, 4];
var ndata = new Uint8Array(nshape[0] * nshape[1] * nshape[2] * nshape[3]);
var result = ndarray(ndata, nshape);
try {
for (var i = 0; i < reader.numFrames(); ++i) {
reader.decodeAndBlitFrameRGBA(
i,
ndata.subarray(result.index(i, 0, 0, 0), result.index(i + 1, 0, 0, 0))
);
}
} catch (err) {
cb(err);
return;
}
cb(null, result.transpose(0, 2, 1));
} else {
var nshape = [reader.height, reader.width, 4];
var ndata = new Uint8Array(nshape[0] * nshape[1] * nshape[2]);
var result = ndarray(ndata, nshape);
try {
reader.decodeAndBlitFrameRGBA(0, ndata);
} catch (err) {
cb(err);
return;
}
cb(null, result.transpose(1, 0));
}
}
function fetchGif(url, cb) {
return fetch(url)
.then(function (response) {
return response.arrayBuffer();
})
.then(function (arrayBuffer) {
return handleGif(new Uint8Array(arrayBuffer), cb);
})
.catch(function (err) {
cb(err);
});
}
module.exports = function getPixels(url, type, cb) {
if (!cb) {
cb = type;
type = "";
}
var ext = path.extname(url);
switch (type || ext.toUpperCase()) {
case ".GIF":
fetchGif(url, cb);
break;
default:
if (Buffer.isBuffer(url)) {
url = "data:" + type + ";base64," + url.toString("base64");
}
if (url.indexOf("data:image/gif;") === 0) {
fetchGif(url, cb);
} else {
defaultImage(url, cb);
}
}
};