forked from pmndrs/postprocessing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRawImageData.js
More file actions
124 lines (85 loc) · 2.1 KB
/
RawImageData.js
File metadata and controls
124 lines (85 loc) · 2.1 KB
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
118
119
120
121
122
123
124
/**
* Creates a new canvas from raw image data.
*
* @private
* @param {Number} width - The image width.
* @param {Number} height - The image height.
* @param {Uint8ClampedArray|Image} data - The image data.
* @return {Canvas} The canvas.
*/
function createCanvas(width, height, data) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
if(data instanceof Image) {
context.drawImage(data, 0, 0);
} else {
const imageData = context.createImageData(width, height);
imageData.data.set(data);
context.putImageData(imageData, 0, 0);
}
return canvas;
}
/**
* A container for raw RGBA image data.
*
* @implements {ImageData}
*/
export class RawImageData {
/**
* Constructs a new image data container.
*
* @param {Number} [width=0] - The width of the image.
* @param {Number} [height=0] - The height of the image.
* @param {Uint8ClampedArray} [data=null] - The image data.
*/
constructor(width = 0, height = 0, data = null) {
/**
* The width of the image.
*
* @type {Number}
*/
this.width = width;
/**
* The height of the image.
*
* @type {Number}
*/
this.height = height;
/**
* The RGBA image data.
*
* @type {Uint8ClampedArray}
*/
this.data = data;
}
/**
* Creates a canvas from this image data.
*
* @return {Canvas} The canvas, or null if it couldn't be created.
*/
toCanvas() {
return (typeof document === "undefined") ? null : createCanvas(this.width, this.height, this.data);
}
/**
* Creates a new image data container.
*
* @param {ImageData|Image} image - An image or plain image data.
* @return {RawImageData} The image data.
*/
static from(image) {
const { width, height } = image;
let data;
if(image instanceof Image) {
const canvas = createCanvas(width, height, image);
if(canvas !== null) {
const context = canvas.getContext("2d");
data = context.getImageData(0, 0, width, height).data;
}
} else {
data = image.data;
}
return new RawImageData(width, height, data);
}
}