Skip to content

Commit 5b0520c

Browse files
committed
fix: indexed color logic
1 parent 87765e7 commit 5b0520c

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

utils/png.js

+12-11
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,10 @@ module.exports = {
100100

101101
const width = view.getUint32(16);
102102
const height = view.getUint32(20);
103-
const bpc = array[24];
104-
const pixel_type = array[25];
105-
let channels = ({ 3: 1, 0: 1, 4: 2, 2: 3, 6: 4 })[pixel_type];
106-
const bytespp = channels * bpc / 8;
103+
let bit_depth = array[24];
104+
const color_type = array[25];
105+
let channels = ({ 3: 1, 0: 1, 4: 2, 2: 3, 6: 4 })[color_type];
106+
const bytespp = channels * bit_depth / 8;
107107

108108
const row_length = width * bytespp;
109109
let pixels = new Uint8Array(height * row_length);
@@ -156,24 +156,25 @@ module.exports = {
156156
p_offset += row_length;
157157
}
158158

159-
if (pixel_type === 3) {
159+
if (color_type === 3) {
160160
if (!palette)
161161
throw new Error('Indexed color PNG has no PLTE');
162162

163163
if (alphaPalette)
164164
for (let i = 0; i < alphaPalette.length; i++)
165165
palette[i] &= 0xffffff00 | alphaPalette[i];
166166

167-
channels = 4;
168167
const newPixels = new Uint8Array(width * height * 4);
169168
const pixelView = new DataView(newPixels.buffer, newPixels.byteOffset, newPixels.byteLength);
170-
for (let i = 0; i < pixels.length; i++)
171-
pixelView.setUint32(i * 4, palette[pixels[i]], false);
169+
for (let i = 0; i < pixels.length * (8 / bit_depth); i++)
170+
pixelView.setUint32(i * 4, palette[pixels[~~(i / (8 / bit_depth))] & (2**bit_depth-1)], false);
171+
channels = 4;
172+
bit_depth = 8;
172173
pixels = newPixels;
173174
}
174175

175-
if (bpc !== 8) {
176-
const newPixels = new Uint8Array(pixels.length / bpc * 8);
176+
if (bit_depth !== 8) {
177+
const newPixels = new Uint8Array(pixels.length / bit_depth * 8);
177178
for (let i = 0; i < pixels.length; i += 2)
178179
newPixels[i / 2] = pixels[i];
179180
pixels = newPixels;
@@ -254,4 +255,4 @@ module.exports = {
254255
}
255256
}
256257
}
257-
};
258+
};

0 commit comments

Comments
 (0)