png-to-rgba
Version:
49 lines (45 loc) • 1.37 kB
text/typescript
import { PNG } from 'pngjs';
export type RGBAarrType = [number, number, number, number][][];
function PNGToRGBAArray(data: Buffer) {
const png = PNG.sync.read(data);
const width = png.width;
const height = png.height;
const pixels = png.data;
const rgba: RGBAarrType = [];
for (let i = 0; i < height; i++) {
rgba[i] = [];
for (let j = 0; j < width; j++) {
const index = (i * width + j) * 4;
rgba[i][j] = [pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]];
}
}
return {
rgba,
width,
height,
png
};
}
function RGBAArrayToPNG(arr: RGBAarrType, opt: import('pngjs').PNGOptions = {}) {
const png = new PNG({
colorType: 6,
inputHasAlpha: true,
...opt,
width: arr[0].length,
height: arr.length,
});
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
const index = (i * arr[i].length + j) * 4;
png.data[index] = arr[i][j][0];
png.data[index + 1] = arr[i][j][1];
png.data[index + 2] = arr[i][j][2];
png.data[index + 3] = arr[i][j][3];
}
}
return PNG.sync.write(png);
}
export default {
PNGToRGBAArray,
RGBAArrayToPNG
}