It's easy to convert JPG and PNG images to Base64 data URLs with JavaScript. Let me show you how.
In case you didn't know, a data URL is simply a long string of characters that represent the binary of your image. You can then use this URL in your HTML <img>
tags.
Very convenient.
Video Tutorial
If you prefer a video tutorial, you can watch this 4 minute video on my YouTube channel:
Step 1. File Input
You'll need a file input field in your HTML. Just like this:
<input type="file" id="fileInput" />
You can name the ID whatever you like.
Step 2. Change Event
In JavaScript, you'll need to attach a change
listener to react to when the user chooses a file.
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", e => {
console.log(e);
});
If you choose a file and check the console, you'll notice the event object. Take note of the target.files
property.
Step 3. File Reader Setup
Next, you'll need to get a reference to the selected file and create a new instance of FileReader
. This file reader object can read files in different forms.
fileInput.addEventListener("change", e => {
const file = fileInput.files[0];
const reader = new FileReader();
});
Replace the console.log
line with the above code.
Step 4. Read as Data URL
Now that we have the FileReader
created, we can tell it to read the file as a Base64 Data URL.
reader.addEventListener("load", () => {
// Base64 Data URL π
console.log(reader.result);
});
reader.readAsDataURL(file);
As you can see we attach the load
event to the FileReader
. Once the file has finished being read, we can grab the Data URL by accessing reader.result
.
Full Code
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", e => {
const file = fileInput.files[0];
const reader = new FileReader();
reader.addEventListener("load", () => {
// Base64 Data URL π
console.log(reader.result);
});
reader.readAsDataURL(file);
});
Done! Feel free to use this Data URL in your <img>
tags. Just don't make the images too large π
Enrol Now π JavaScript DOM Crash Course
If you're learning web development, you can find a complete course on the JavaScript DOM at the link below π
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1
Top comments (1)
Thanks!