Skip to content

Instantly share code, notes, and snippets.

@MarkoCen
Last active December 8, 2023 09:59
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save MarkoCen/0ee9437439e00e313926 to your computer and use it in GitHub Desktop.
Save MarkoCen/0ee9437439e00e313926 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}`;
})
}
@gendalf-thug
Copy link

Thank you you helped me a lot😘

@AjayPoshak
Copy link

Thanks for putting this out. Saved me a lot of trouble. ❤️

@StevenWinnie
Copy link

StevenWinnie commented Aug 3, 2023

Thanks for this code conversion! Though it looks a bit difficult to me as I am a beginner in coding. I've started to learn more about image formats, compression, and conversion... Check this post to learn more about PNG and is PNG a lossless compression. Thanks again for your help!

@John777R
Copy link

John777R commented Dec 8, 2023

Reading the image went fine, thanks for the code conversion, it helped work better with college studying images https://depositphotos.com/photos/college-studying.html Although it seems difficult, it brings certain successes and it is worth saying that for a beginner in programming it is quite difficult to do, but it is possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment