Converting an Image to a Data URI String in Node.js
In this short article, we'll explore how to convert an image into a Data URI string in Node.js.
Converting an image to a Data URI string involves reading the image file, converting it to a base64 string, and constructing the Data URI.
Here's how I created a function to do it:
const fs = require('fs'); // Create a function that takes an image path as a parameter function toDataUri(imgPath) { // Read data const bitmap = fs.readFileSync(imgPath); // convert binary data to base64 encoded string const base64Image = Buffer.from(bitmap).toString('base64'); // Get image file extension const ext = imgPath.split('.').pop(); // complete data URI const uri = `data:image/${ext};base64,${base64Image}`; return uri; } // Outputs your image URI console.log(toDataUri('./path/to/your/image.jpg'));
This script reads the image file, converts it to base64, and then constructs the Data URI. The imageToDataUri function takes the path to an image file as an argument and returns the Data URI string.
And that's it!
This simple function lets you easily convert any image to a Data URI string in Node.js. Happy coding!
Note
This example assumes that the image file extension matches the image MIME type (e.g., 'jpg' for 'image/jpeg').
If you're dealing with images that might not follow this convention, you might need to use a library or additional code to determine the correct MIME type based on the image data.
Follow me on Twitter or connect on LinkedIn.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉