How to Convert Image to Base64 in JavaScript & Python
Skip the code and convert your images (PNG, JPG, SVG, WebP) to Base64 strings locally and privately right now.
Open Image to Base64 Converter →Encoding images as Base64 strings is a common practice in web development. It allows you to embed images directly into your HTML or CSS files, reducing the number of HTTP requests your page has to make. In this guide, we will explore how to perform this conversion programmatically using JavaScript and Python.
What is Base64 Image Encoding?
Base64 is a binary-to-text encoding scheme. When you convert an image (like a PNG or JPEG) to Base64, you convert the image's raw binary data into a string of 64 ASCII characters. This string can then be formatted as a Data URI:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...
You can paste this string directly into the src attribute of an HTML image tag or a CSS background-image property.
1. Converting Image to Base64 in JavaScript
On the client side (in the browser), you can use the HTML5 FileReader API to read a user-selected image file as a Base64 string:
// HTML: <input type="file" id="imageInput">
const input = document.getElementById('imageInput');
input.addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result;
console.log('Base64 String:', base64String);
// You can now use this string as img.src
};
reader.readAsDataURL(file);
});
2. Converting Image to Base64 in Python
On the backend or in scripting scripts, Python makes it very easy to encode image files using the built-in base64 module:
import base64
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
# Read the binary data of the image
binary_data = image_file.read()
# Encode binary data to base64 bytes
base64_bytes = base64.b64encode(binary_data)
# Convert bytes to a readable UTF-8 string
base64_string = base64_bytes.decode('utf-8')
return base64_string
# Example Usage
encoded_image = image_to_base64("logo.png")
print(f"data:image/png;base64,{encoded_image[:50]}...")
Pros and Cons of Base64 Images
Advantages:
- Fewer HTTP Requests: The image loads with the HTML, saving connection overhead.
- Offline Capability: Useful for offline email newsletters, single-file templates, or PWA assets.
- Portability: Easy to move data without managing image asset folders.
Disadvantages:
- File Size Increase: Base64 strings are roughly 33% larger than the raw binary files.
- No Caching: Browsers cannot cache the image separately from the HTML document.
Convert Images Instantly Offline
To convert images without coding, use our local Image to Base64 Converter. Just drag and drop your files to get the code instantly.