Skip to content

Instantly share code, notes, and snippets.

@guilhermebkel
Created June 28, 2020 14:41
Show Gist options
  • Save guilhermebkel/7e9799a489c54344bf8bb07abc8153c1 to your computer and use it in GitHub Desktop.
Save guilhermebkel/7e9799a489c54344bf8bb07abc8153c1 to your computer and use it in GitHub Desktop.
Make picture background transparent
const { promisify } = require('util')
const { resolve } = require('path')
const fs = require('fs')
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
const sharp = require("sharp")
const replaceColor = require('replace-color')
async function process(path) {
if (path.includes("cards-raw")) {
path = path.split("cards-raw").pop()
}
const prodFolder = "./cards-correct"
const rawFolder = "./cards-raw"
try {
const picture = await sharp(`${rawFolder}/main.png`).withMetadata().toBuffer()
const SIZE = 400
const width = SIZE
const height = SIZE
const channels = 4
const rgbaPixel = 0x00000000
const canvas = Buffer.alloc(width * height * channels, rgbaPixel)
let processedPicture = await sharp(canvas, { create: { width: SIZE, height: SIZE, channels: 3, background: "#252525" }})
.composite([{ input: picture, gravity: "center" }])
.withMetadata()
.png()
.toBuffer()
processedPicture = await new Promise(resolve => {
replaceColor({
image: processedPicture,
colors: {
type: "hex",
targetColor: "#252525",
replaceColor: "#ff00e5"
}
}, (error, jimpObject) => {
jimpObject.write(`${prodFolder}${path}`, (async callback => {
const pic = await sharp(`${prodFolder}${path}`).withMetadata().toBuffer()
resolve(pic)
}))
})
})
processedPicture = await sharp(processedPicture)
.trim()
.toBuffer()
await new Promise(resolve => {
replaceColor({
image: processedPicture,
colors: {
type: "rgb",
targetColor: [255, 0, 229],
replaceColor: [255, 0, 229, 0]
},
deltaE: 10
}, (error, jimpObject) => {
jimpObject.write(`${prodFolder}${path}`, resolve)
})
})
} catch(error) {
console.error(error)
}
}
async function getFiles(dir) {
const subdirs = await readdir(dir)
const files = await Promise.all(subdirs.map(async (subdir) => {
const res = resolve(dir, subdir)
return (await stat(res)).isDirectory() ? getFiles(res) : res
}))
return files.reduce((a, f) => a.concat(f), [])
}
async function start() {
let files = await getFiles("./cards-raw")
files = files.map(file => {
return `./cards-raw${file.split("cards-raw").pop()}`
})
await Promise.all(
files.map(file => process(file))
)
console.log("ACABOU!")
}
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment