Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert an Image to blob using JavaScript?
Converting an image to a blob in JavaScript allows you to work with binary image data for file uploads, downloads, or processing. A blob (Binary Large Object) represents immutable binary data that can be read as text or binary data.
What is a Blob?
A blob is a file-like object that contains raw binary data. When you convert an image to a blob, you get access to properties like size and MIME type, making it useful for file operations.
Using fetch() to Convert Image URL to Blob
The most common approach is using the fetch API to retrieve an image and convert the response to a blob:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convert Image to Blob</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
margin-top: 15px;
}
img {
max-width: 300px;
border: 2px solid #ddd;
margin: 10px 0;
}
button {
background: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Convert Image to Blob</h1>
<div class="sample">
<img src="https://picsum.photos/id/222/300/300.jpg" alt="Sample Image">
</div>
<button class="convert-btn">Convert to Blob</button>
<div class="result"></div>
<h3>Click the button to convert the image above to a blob</h3>
<script>
let convertBtn = document.querySelector(".convert-btn");
let resultDiv = document.querySelector(".result");
convertBtn.addEventListener("click", () => {
// Fetch the image and convert to blob
fetch("https://picsum.photos/id/222/300/300.jpg")
.then(function (response) {
return response.blob();
})
.then(function (blob) {
// Display blob information
resultDiv.innerHTML = "Blob Size: " + blob.size + " bytes<br>";
resultDiv.innerHTML += "Blob Type: " + blob.type + "<br>";
resultDiv.innerHTML += "Conversion successful!";
console.log("Blob created:", blob);
})
.catch(function (error) {
resultDiv.innerHTML = "Error converting image: " + error.message;
});
});
</script>
</body>
</html>
How It Works
The conversion process involves these steps:
-
Fetch the image: Use
fetch()to retrieve the image from its URL - Get response: The fetch returns a Response object
-
Convert to blob: Call
response.blob()to extract binary data -
Access blob properties: Use
blob.sizeandblob.typefor information
Using Canvas to Convert Image Element to Blob
You can also convert an existing image element to a blob using canvas:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Image to Blob</title>
</head>
<body>
<img id="sourceImage" src="https://picsum.photos/200/200" crossorigin="anonymous">
<button onclick="convertCanvasToBlob()">Convert via Canvas</button>
<div id="canvasResult"></div>
<script>
function convertCanvasToBlob() {
const img = document.getElementById('sourceImage');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to match image
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
// Draw image on canvas
ctx.drawImage(img, 0, 0);
// Convert canvas to blob
canvas.toBlob(function(blob) {
document.getElementById('canvasResult').innerHTML =
"Canvas Blob Size: " + blob.size + " bytes<br>" +
"Canvas Blob Type: " + blob.type;
console.log("Canvas blob:", blob);
}, 'image/jpeg', 0.8); // JPEG format with 80% quality
}
</script>
</body>
</html>
Common Use Cases
- File uploads: Convert images to blobs before uploading via FormData
- Image processing: Manipulate binary image data
- Download functionality: Create downloadable image files
- Caching: Store image data locally in browsers
Key Points
- Use
fetch().then(response => response.blob())for URL-to-blob conversion - Canvas method allows format and quality control
- CORS policy may restrict cross-origin image conversion
- Blobs are immutable - create new ones for modifications
Conclusion
Converting images to blobs enables powerful client-side file operations. Use fetch() for simple URL conversion or canvas for more control over the output format and quality.
