Skip to content

Commit

Permalink
fix: indexed color logic
Browse files Browse the repository at this point in the history
  • Loading branch information
matmen committed Mar 24, 2024
1 parent 87765e7 commit 5b0520c
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions utils/png.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ module.exports = {

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

const row_length = width * bytespp;
let pixels = new Uint8Array(height * row_length);
Expand Down Expand Up @@ -156,24 +156,25 @@ module.exports = {
p_offset += row_length;
}

if (pixel_type === 3) {
if (color_type === 3) {
if (!palette)
throw new Error('Indexed color PNG has no PLTE');

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

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

if (bpc !== 8) {
const newPixels = new Uint8Array(pixels.length / bpc * 8);
if (bit_depth !== 8) {
const newPixels = new Uint8Array(pixels.length / bit_depth * 8);
for (let i = 0; i < pixels.length; i += 2)
newPixels[i / 2] = pixels[i];
pixels = newPixels;
Expand Down Expand Up @@ -254,4 +255,4 @@ module.exports = {
}
}
}
};
};

0 comments on commit 5b0520c

Please sign in to comment.