/
colorDepth.js
61 lines (56 loc) · 1.62 KB
/
colorDepth.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
import Image from '../Image';
/**
* Change the image color depth.
* The color depth is the number of bits that is assigned to each point of a channel.
* For normal images it is 8 bits meaning the value is between 0 and 255.
* Currently only conversion from 1, 8 or 16 bits towards 8 or 16 bits are allowed.
* @memberof Image
* @instance
* @param {number} [newColorDepth=8]
* @return {Image} The new image
* @example
* var newImage = image.colorDepth(8);
*/
export default function colorDepth(newColorDepth = 8) {
this.checkProcessable('colorDepth', {
bitDepth: [1, 8, 16],
});
if (![8, 16].includes(newColorDepth)) {
throw Error('You need to specify the new colorDepth as 8 or 16');
}
if (this.bitDepth === newColorDepth) {
return this.clone();
}
let newImage = Image.createFrom(this, { bitDepth: newColorDepth });
switch (newColorDepth) {
case 8:
if (this.bitDepth === 1) {
for (let i = 0; i < this.size; i++) {
if (this.getBit(i)) {
newImage.data[i] = 255;
}
}
} else {
for (let i = 0; i < this.data.length; i++) {
newImage.data[i] = this.data[i] >> 8;
}
}
break;
case 16:
if (this.bitDepth === 1) {
for (let i = 0; i < this.size; i++) {
if (this.getBit(i)) {
newImage.data[i] = 65535;
}
}
} else {
for (let i = 0; i < this.data.length; i++) {
newImage.data[i] = (this.data[i] << 8) | this.data[i];
}
}
break;
default:
throw new Error('colorDepth conversion unexpected case');
}
return newImage;
}