Skip to content

Instantly share code, notes, and snippets.

@jimbrig
Forked from MarkoCen/convertImgToBase64.js
Created September 25, 2024 20:56
Show Gist options
  • Save jimbrig/5b443a71e1c5968bf8e311a48d736e38 to your computer and use it in GitHub Desktop.
Save jimbrig/5b443a71e1c5968bf8e311a48d736e38 to your computer and use it in GitHub Desktop.
Read Image (PNG/JPEG) From Disk and Convert it to base64-encoded string on Node Server
import fs from 'fs';
import path from 'path';
const convert = (imgPath) => {
// read image file
fs.readFile(imgPath, (err, data)=>{
// error handle
if(err) {
throw err;
}
// get image file extension name
const extensionName = path.extname(imgPath);
// convert image file to base64-encoded string
const base64Image = Buffer.from(data, 'binary').toString('base64');
// combine all strings
const base64ImageStr = `data:image/${extensionName.split('.').pop()};base64,${base64Image}`;
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment