Skip to content

Instantly share code, notes, and snippets.

@ruvasik
Created October 11, 2022 19:53
Show Gist options
  • Save ruvasik/f9389fa0454012102eb926514447417b to your computer and use it in GitHub Desktop.
Save ruvasik/f9389fa0454012102eb926514447417b to your computer and use it in GitHub Desktop.
JS image to/from data URI
import fs from "fs";
export const imageToDataUri = (image: string | Buffer): string | undefined => {
const extTypeMap = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'webp': 'image/webp'
};
let base64;
if (typeof image === 'string') {
try {
base64 = fs.readFileSync(image, 'base64')
return `data:${extTypeMap[image.split('.').pop()]};base64,${base64}`;
}
catch (e) {
console.log(e);
return undefined;
}
}
else if (Buffer.isBuffer(image)) {
base64 = image.toString('base64');
return `data:image/jpeg;base64,${base64}`;
}
}
export const imageFromDataUri = (dataUri: string, url?: string) => {
const data = new Buffer(dataUri.substring((dataUri.indexOf('base64,') || 0) + 7), 'base64');
if (!url)
return data;
try {
fs.writeFileSync(url, data);
}
catch (e) {
console.log(e);
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment