Skip to content

Instantly share code, notes, and snippets.

@mobyjames
Last active January 26, 2021 18:00
Show Gist options
  • Save mobyjames/94c75fca3185c46e12deae24d12df114 to your computer and use it in GitHub Desktop.
Save mobyjames/94c75fca3185c46e12deae24d12df114 to your computer and use it in GitHub Desktop.
Render pixel art in NodeJS
import { pallet } from './pallet';
import sharp from 'sharp';
export async function renderCharacter(pixels: Array<number>) {
const width = 20;
const height = 20;
// create raw pixel buffer
// pixels are stored as numbers in red, green, blue, alpha format
// starting in top left
const buffer = await sharp({
create: {
width,
height,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 1 },
},
})
.raw()
.toBuffer();
// iterate pixels in 4-number blocks converting values from index colors to rgba
for (let i = 0; i < pixels.length; i++) {
const palletIndex = pixels[i];
const color = pallet[palletIndex];
const p = i * 4;
buffer[p] = color[0];
buffer[p + 1] = color[1];
buffer[p + 2] = color[2];
buffer[p + 3] = color[3];
}
// convert the raw pixels to png format
const png = await sharp(buffer, { raw: { width: 20, height: 20, channels: 4 } })
.resize(400, 400, { kernel: sharp.kernel.nearest })
.png()
.toBuffer();
return png;
}
// example pallet... could have more colors
export const pallet = [
[255, 180, 195, 0xff],
[255, 204, 153, 0xff],
[255, 255, 153, 0xff],
[204, 255, 204, 0xff],
[204, 255, 255, 0xff],
[153, 204, 255, 0xff],
[204, 204, 255, 0xff],
[255, 204, 255, 0xff],
[241, 224, 206, 0xff],
[255, 255, 255, 0xff],
[255, 0, 0, 0xff],
[255, 153, 51, 0xff],
[255, 255, 0, 0xff],
[0, 204, 0, 0xff],
[0, 255, 255, 0xff],
[51, 153, 255, 0xff],
[153, 0, 255, 0xff],
[255, 0, 255, 0xff],
[224, 194, 163, 0xff],
[214, 214, 214, 0xff],
[197, 0, 0, 0xff],
[228, 114, 0, 0xff],
[222, 214, 0, 0xff],
[0, 160, 0, 0xff],
[0, 202, 202, 0xff],
[0, 102, 204, 0xff],
[114, 14, 185, 0xff],
[180, 0, 180, 0xff],
[166, 132, 76, 0xff],
[102, 102, 102, 0xff],
[140, 0, 0, 0xff],
[175, 87, 0, 0xff],
[160, 160, 0, 0xff],
[0, 92, 0, 0xff],
[0, 110, 120, 0xff],
[0, 60, 114, 0xff],
[80, 0, 114, 0xff],
[120, 0, 120, 0xff],
[82, 58, 20, 0xff],
[0, 0, 0, 0xff],
[0, 0, 0, 0x00],
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment