Created
February 21, 2026 23:55
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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