UNPKG

2.37 kBJavaScriptView Raw
1"use strict";
2
3function dePalette(indata, outdata, width, height, palette) {
4 let pxPos = 0;
5 // use values from palette
6 for (let y = 0; y < height; y++) {
7 for (let x = 0; x < width; x++) {
8 let color = palette[indata[pxPos]];
9
10 if (!color) {
11 throw new Error("index " + indata[pxPos] + " not in palette");
12 }
13
14 for (let i = 0; i < 4; i++) {
15 outdata[pxPos + i] = color[i];
16 }
17 pxPos += 4;
18 }
19 }
20}
21
22function replaceTransparentColor(indata, outdata, width, height, transColor) {
23 let pxPos = 0;
24 for (let y = 0; y < height; y++) {
25 for (let x = 0; x < width; x++) {
26 let makeTrans = false;
27
28 if (transColor.length === 1) {
29 if (transColor[0] === indata[pxPos]) {
30 makeTrans = true;
31 }
32 } else if (
33 transColor[0] === indata[pxPos] &&
34 transColor[1] === indata[pxPos + 1] &&
35 transColor[2] === indata[pxPos + 2]
36 ) {
37 makeTrans = true;
38 }
39 if (makeTrans) {
40 for (let i = 0; i < 4; i++) {
41 outdata[pxPos + i] = 0;
42 }
43 }
44 pxPos += 4;
45 }
46 }
47}
48
49function scaleDepth(indata, outdata, width, height, depth) {
50 let maxOutSample = 255;
51 let maxInSample = Math.pow(2, depth) - 1;
52 let pxPos = 0;
53
54 for (let y = 0; y < height; y++) {
55 for (let x = 0; x < width; x++) {
56 for (let i = 0; i < 4; i++) {
57 outdata[pxPos + i] = Math.floor(
58 (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5
59 );
60 }
61 pxPos += 4;
62 }
63 }
64}
65
66module.exports = function (indata, imageData, skipRescale = false) {
67 let depth = imageData.depth;
68 let width = imageData.width;
69 let height = imageData.height;
70 let colorType = imageData.colorType;
71 let transColor = imageData.transColor;
72 let palette = imageData.palette;
73
74 let outdata = indata; // only different for 16 bits
75
76 if (colorType === 3) {
77 // paletted
78 dePalette(indata, outdata, width, height, palette);
79 } else {
80 if (transColor) {
81 replaceTransparentColor(indata, outdata, width, height, transColor);
82 }
83 // if it needs scaling
84 if (depth !== 8 && !skipRescale) {
85 // if we need to change the buffer size
86 if (depth === 16) {
87 outdata = Buffer.alloc(width * height * 4);
88 }
89 scaleDepth(indata, outdata, width, height, depth);
90 }
91 }
92 return outdata;
93};