Skip to content

Instantly share code, notes, and snippets.

@AnonymerNiklasistanonym
Created February 19, 2024 21:30
Show Gist options
  • Save AnonymerNiklasistanonym/e658bbeba6cb22a5cd5f1c5beff50651 to your computer and use it in GitHub Desktop.
Save AnonymerNiklasistanonym/e658bbeba6cb22a5cd5f1c5beff50651 to your computer and use it in GitHub Desktop.
Add colored stroke around objects in transparent (.png) image
{
"dependencies": {
"sharp": "^0.33.2",
"ts-node": "^10.9.2"
},
"scripts": {
"start": "ts-node script.ts"
}
}
// Add colored stroke around objects in transparent (.png) image
import sharp from 'sharp'
import type { Sharp } from 'sharp'
// Based on a code snippet from arunlodhi in the GitHub sharp repository
// https://github.com/lovell/sharp/issues/3759
const drawOutlineSharp = async (
sharpInstance: Sharp,
thickness: number = 10,
blurSigma: number = 2,
outlineColor = { r: 255, g: 0, b: 0, alpha: 1 }
): Promise<Sharp> => {
const inputBuffer = await sharpInstance.toBuffer()
const alphaMask = sharpInstance.clone().extractChannel("alpha").png()
const negatedAlphaMask = sharp(
await alphaMask.clone().blur(blurSigma).negate().toBuffer()
)
//negatedAlphaMask.toFile(("negatedAlphaMask.png"))
const bgMask = negatedAlphaMask.blur(thickness / 2).unflatten()
//bgMask.toFile(("bgMask.png"))
let bg = bgMask.composite([
{
input: {
create: {
width: 1,
height: 1,
channels: 4,
background: outlineColor,
},
},
blend: "in",
tile: true,
},
])
bg = sharp(await bg.toBuffer())
bg = bg.composite([
{
input: inputBuffer,
blend: "over",
},
])
//bg.toFile(("bg.png"))
return sharp(await bg.toBuffer())
}
const drawOutline = async (
inImgPath: string,
outImgPath: string,
thickness: number = 20,
blurSigma: number = 10,
outlineColor = { r: 255, g: 255, b: 255, alpha: 1 }
) => {
drawOutlineSharp(sharp(inImgPath), thickness, blurSigma, outlineColor)
.then((buf) => buf.toFile(outImgPath))
.then((info) => console.info(`Exported image (${outImgPath}) information:`, info))
.catch((err) => console.error(err))
}
// Demo:
drawOutline(
"/home/niklas/OneDrive/Andere Dateien/osu/aubs-borgar.png",
"/home/niklas/OneDrive/Andere Dateien/osu/aubs-borgar_edited.png"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment