Convert Image to Base64
Convert an image file to a Base64-encoded string, which can be used for embedding images directly in HTML, CSS, or JSON.
POST
/api/image/to-base64
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
file | File | Yes | The image file to convert to Base64. Supported formats: JPEG, PNG, WebP, BMP, TIFF, GIF, SVG. |
Response
Returns a JSON object containing the Base64-encoded image string and related information.
Example Request
// example.sh
curl -X POST "https://oyyi.xyz/api/image/to-base64" \
-H "accept: application/json" \
-H "Content-Type: multipart/form-data" \
-F "file=@image.jpg" \
-F "include_mime=true"
Example with Python
// to_base64.py
import requests
import json
url = "https://oyyi.xyz/api/image/to-base64"
files = {
'file': open('image.jpg', 'rb')
}
data = {
'include_mime': True
}
response = requests.post(url, files=files, data=data)
# Parse the JSON response
base64_data = response.json()
print(f"MIME Type: {base64_data['mime_type']}")
print(f"Base64 String (first 50 chars): {base64_data['base64'][:50]}...")
# Use the base64 string in HTML
html_img = '<img src="' + base64_data["data_uri"] + '" alt="Base64 encoded image" />'
with open('image.html', 'w') as f:
f.write(f'<!DOCTYPE html><html><body>{html_img}</body></html>')
print("Created HTML file with embedded image")
Example with JavaScript
// to_base64.js
// Using fetch API
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('include_mime', 'true');
fetch('https://oyyi.xyz/api/image/to-base64', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(base64Data => {
console.log('MIME Type:', base64Data.mime_type);
console.log('Base64 String (first 50 chars):', base64Data.base64.substring(0, 50) + '...');
// Display the image using the data URI
const img = document.createElement('img');
img.src = base64Data.data_uri;
img.alt = 'Base64 encoded image';
document.body.appendChild(img);
})
.catch(error => console.error('Error:', error));
Example Response
// response.json
{
"base64": "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/...",
"mime_type": "image/jpeg",
"data_uri": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/...",
"size_bytes": 24576,
"size_formatted": "24.0 KB"
}
Response Structure
Field | Description |
---|---|
base64 | The Base64-encoded string representation of the image. |
mime_type | The MIME type of the image (e.g., "image/jpeg", "image/png"). Only included if include_mime is true. |
data_uri | A complete data URI that can be used directly in HTML img tags or CSS background-image properties. Only included if include_mime is true. |
size_bytes | The size of the Base64-encoded string in bytes. |
size_formatted | The size of the Base64-encoded string in a human-readable format (e.g., "24.0 KB"). |
How It Works
The to-base64 endpoint converts an image file to a Base64-encoded string:
- Image Loading: The uploaded image file is loaded into memory.
- Resizing (Optional): If resize is true, the image is resized to fit within the specified max_width and max_height while maintaining the aspect ratio.
- Base64 Encoding: The image binary data is encoded using Base64 encoding, which represents binary data as ASCII text using a set of 64 characters.
- MIME Type Detection: If include_mime is true, the MIME type of the image is detected based on the file format.
- Data URI Creation: If include_mime is true, a complete data URI is created by combining the MIME type and Base64 string.
- Size Calculation: The size of the Base64-encoded string is calculated and formatted.
The result is a Base64-encoded representation of the image that can be used in various web applications without requiring a separate image file.
Error Responses
Status Code | Description |
---|---|
400 | Bad request. Missing required parameters, invalid include_mime value, invalid resize value, invalid max_width/max_height values, invalid quality value, or invalid file format. |
413 | Payload too large. The file size exceeds the maximum allowed limit. |
500 | Internal server error. Something went wrong on the server. |
Notes
- Base64 encoding increases the file size by approximately 33% compared to the original binary data.
- For large images, consider using the resize option to reduce the size of the Base64 string.
- The data URI format is supported by all modern browsers and can be used directly in HTML, CSS, and JavaScript.
- Base64-encoded images are loaded immediately without requiring an additional HTTP request, which can improve page load times for small images.
- However, Base64-encoded images cannot be cached separately by the browser, so they're redownloaded with each page load.
- The maximum file size allowed is 10MB, but keep in mind that large Base64 strings can impact performance.
- SVG images are already text-based and can be efficiently encoded as Base64.
Use Cases
- Embedding small images directly in HTML or CSS to reduce HTTP requests
- Including images in JSON API responses
- Creating data URIs for use in email templates
- Storing images in databases that don't support binary data
- Creating self-contained HTML documents with embedded images
- Generating QR codes or barcodes that can be embedded directly
- Creating image previews for web applications
- Embedding icons or logos in single-file web applications