Skip to content

Instantly share code, notes, and snippets.

@quietsamurai98
Created February 21, 2026 23:55
Show Gist options
  • Select an option

  • Save quietsamurai98/5966e674b1fe152d0aad32e4fc7ee542 to your computer and use it in GitHub Desktop.

Select an option

Save quietsamurai98/5966e674b1fe152d0aad32e4fc7ee542 to your computer and use it in GitHub Desktop.
NodeJS util to swap opaque lightness for black transparency in a grayscale image. Useful for making stickman images on a white background transparent.
const { Jimp, intToRGBA } = require("jimp");
function rgba_to_hex(r, g, b ,a) {
return ((r*256+g)*256+b)*256+a;
}
/**
* grayscale image with transparent background.
* @param inputPath Path to the input image.
* @param outputPath Path to write the output image to.
* @param maxOpacity Number from 1-255. Pure black on the input image will be converted to RGBA of [blackLightness,blackLightness,blackLightness,maxOpacity]
* @param blackLightness Number from 0 to 255. Pure black on the input image will be converted to RGBA of [blackLightness,blackLightness,blackLightness,maxOpacity]
* @returns {Promise<void>}
*/
async function convert(inputPath, outputPath, maxOpacity = 255, blackLightness = 0){
const image = await Jimp.read(inputPath);
image.greyscale();
const output = new Jimp({ width: image.width, height: image.height, color: 0xff00ff88 });
for (let x = 0; x < image.width; x++) {
for (let y = 0; y < image.height; y++) {
let pixelColor = image.getPixelColor(x, y);
let c = intToRGBA(pixelColor);
let alpha = Math.floor((255 - c.r)/(256-maxOpacity));
let newColor = rgba_to_hex(blackLightness, blackLightness, blackLightness, alpha);
output.setPixelColor(newColor, x, y);
}
}
await output.write(outputPath);
}
const args = process.argv.slice(2);
convert(args[0], args[1], parseInt(args[2] || '255'), parseInt(args[3] || '0')).then(r => console.log('Done!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment