Last active
July 19, 2024 07:28
-
-
Save sou-long/5c7cfee57f5399918c9072552afe2ec8 to your computer and use it in GitHub Desktop.
Dodging all the bullets with @imgly/background-removal-node
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
| import fs from 'node:fs' | |
| import path from 'node:path' | |
| import url from 'node:url' | |
| import {removeBackground} from '@imgly/background-removal-node' | |
| const P = (...vs: string[]) => path.resolve(...vs) | |
| async function remove_bg(filename: string) { | |
| const prj_dir = P(url.fileURLToPath(import.meta.url), '../..') // assuming we're in src/foo.ts | |
| const dist_dir = P(prj_dir, 'node_modules/@imgly/background-removal-node/dist') | |
| const config = { | |
| // receives file url as a string, slash is required | |
| // won't work outside of `prj_dir` if not specified | |
| publicPath: url.pathToFileURL(dist_dir).toString() + '/', | |
| } | |
| // only works with a typed Blob (file url, string, Buffer, bare Blob failed) | |
| const in_data = await fs.promises.readFile(P(filename)) | |
| const ext = path.parse(filename).ext.replace('.', '') | |
| const in_blob = new Blob([in_data], {type:'image/'+ext}) | |
| const out_blob = await removeBackground(in_blob, config) | |
| const out_data = Buffer.from(await out_blob.arrayBuffer()) | |
| const out_filename = filename.replace(/\.\w+$/, '-nobg.png') // 'test.jpg' -> 'test-nobg.png' | |
| await fs.promises.writeFile(out_filename, out_data) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment