To convert an image to a Base64 string in JavaScript, you can use either the FileReader API (for user-uploaded files) or the Canvas API (for existing images in the DOM). Below are detailed explanations and examples for both methods:
Method 1: Using FileReader API (for <input type="file">
)
Ideal for converting user-uploaded images from an <input>
element.
Step-by-Step:
- User selects an image via
<input type="file">
. - Read the file using
FileReader.readAsDataURL()
. - Get Base64 string from
FileReader.result
.
Example Code:
<input type="file" id="imageInput" accept="image/*">
<script>
document.getElementById('imageInput').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(event) {
const base64String = event.target.result;
console.log(base64String); // "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
};
reader.readAsDataURL(file);
});
</script>
Output Format:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/...
- Prefix:
data:image/jpeg;base64,
(MIME type + encoding). - Base64 Data: The string after the comma.
Method 2: Using Canvas API (for <img>
elements)
Converts an existing <img>
element (even dynamically loaded) to Base64.
⚠️ Requires CORS compliance if the image is cross-origin.
Step-by-Step:
- Load the image (ensure it’s fully loaded).
- Draw the image onto a
<canvas>
. - Convert canvas to Base64 using
canvas.toDataURL()
.
Example Code:
<img id="myImage" src="image.jpg" crossorigin="anonymous"> <!-- Enable CORS -->
<script>
const img = document.getElementById('myImage');
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to the image's size
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
// Draw image onto canvas
ctx.drawImage(img, 0, 0);
// Get Base64 string (default: PNG)
const base64String = canvas.toDataURL('image/jpeg', 0.8); // Format + quality
console.log(base64String);
};
// If image is already loaded, trigger onload manually
if (img.complete) img.dispatchEvent(new Event('load'));
</script>
Parameters for toDataURL()
:
type
:image/png
(default),image/jpeg
,image/webp
.quality
: Number from0
to1
(JPEG/WebP compression).
Key Notes
- CORS Restrictions:
- For Canvas: Add
crossorigin="anonymous"
to<img>
and ensure the server supports CORS. - FileReader doesn’t require CORS (user-uploaded files are local).
- Extract Base64 Data Only:
const base64Data = base64String.split(',')[1]; // Remove prefix
- Performance:
- Canvas method is slower but allows format/quality control.
- FileReader is faster for direct conversions.
Dynamic Image Example (No DOM)
Convert an image from a URL without adding it to the page:
function imageToBase64(url, callback) {
const img = new Image();
img.crossOrigin = 'anonymous'; // Enable CORS
img.src = url;
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
callback(canvas.toDataURL('image/png'));
};
}
// Usage
imageToBase64('https://example.com/image.jpg', base64 => {
console.log(base64);
});
Use Cases
- FileReader: Uploading user images (profile pictures, etc.).
- Canvas: Converting existing images (e.g., from galleries) or editing images before conversion.
Choose the method based on your image source and requirements!