Keywords: JavaScript | Blob | Base64 Encoding | Image Display | Data Conversion
Abstract: This paper provides an in-depth exploration of technical solutions for properly handling and displaying Blob image data in JavaScript. By analyzing common Base64 encoding issues, it focuses on the critical steps of converting hexadecimal data to binary, and comprehensively compares multiple implementation methods including XMLHttpRequest and Fetch API. Integrating MDN official documentation, the article systematically explains the characteristics of Blob objects, creation methods, and data extraction techniques, offering complete solutions and best practice guidelines for front-end developers.
Core Issues in Blob Image Display
In web development, retrieving Blob image data from databases or other data sources and correctly displaying it in browsers is a common requirement. Many developers encounter image display failures when using Base64 encoding, often due to incomplete data format conversion.
Key Technical Points of Base64 Encoding
Using Base64.encode(blob) directly to encode Blob objects in original code often fails to work properly because Blob data may be stored in hexadecimal format and needs to be converted to binary data first. The correct processing flow should be:
// Pseudo-code example: Hexadecimal to binary conversion
function hexToBinary(hexString) {
const bytes = new Uint8Array(hexString.length / 2);
for (let i = 0; i < hexString.length; i += 2) {
bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
}
return bytes;
}
// Convert binary data to Base64
function binaryToBase64(binaryData) {
return btoa(String.fromCharCode(...binaryData));
}
In PHP backend environments, base64_encode(pack("H*", $subvalue)) can be used to complete the same conversion process, where pack("H*", $subvalue) converts hexadecimal strings to binary data.
In-depth Understanding of Blob Objects
According to MDN documentation, the Blob (Binary Large Object) interface represents immutable raw data objects that can store text or binary data. Blob objects have the following important characteristics:
- Immutability: Once created, the content of Blob objects cannot be changed
- Multi-format Support: Can represent data in non-JavaScript native formats
- File Foundation: The File interface is based on Blob, extending file system support
Comparison of Multiple Implementation Solutions
Solution 1: XMLHttpRequest with Object URL
Using XMLHttpRequest to directly obtain Blob data and create temporary URLs through URL.createObjectURL():
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/image");
xhr.responseType = "blob";
xhr.onload = function() {
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(this.response);
document.getElementById("image").src = imageUrl;
};
xhr.send();
Solution 2: Fetch API Implementation
Using modern Fetch API to obtain and process Blob data:
const myImage = document.querySelector('img');
fetch('/api/image')
.then(response => response.blob())
.then(myBlob => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
})
.catch(error => console.error('Fetch error:', error));
Blob Data Extraction Techniques
Beyond direct image display, sometimes data needs to be extracted from Blob for analysis or processing:
Using FileReader to Read Data
const reader = new FileReader();
reader.addEventListener("loadend", () => {
// reader.result contains the Blob content as a typed array
console.log("Blob data:", reader.result);
});
reader.readAsArrayBuffer(blob);
Using Response Object to Read Text
async function readBlobAsText(blob) {
const text = await new Response(blob).text();
return text;
}
// Or using Blob.text() method
async function readBlobText(blob) {
const text = await blob.text();
return text;
}
Performance Optimization and Memory Management
URLs created using URL.createObjectURL() occupy memory and need to be released via URL.revokeObjectURL() when no longer needed:
const imageUrl = URL.createObjectURL(blob);
imageElement.src = imageUrl;
// When the image is no longer needed
imageElement.onload = function() {
URL.revokeObjectURL(imageUrl);
};
Compatibility Considerations
The Blob API is widely supported in modern browsers, but may require polyfills in older browsers. Major browsers have generally supported Blob functionality since July 2015, including usage in Web Workers.
Practical Application Scenarios
These technologies are applicable not only to image display but also to:
- PDF file preview
- Audio/video file playback
- Custom file downloads
- Data stream processing
Conclusion
Properly handling Blob image display requires understanding the complete data format conversion process. Converting from hexadecimal to binary is a key step in solving Base64 encoding issues. Meanwhile, developers should choose appropriate APIs (XMLHttpRequest or Fetch API) based on specific requirements and pay attention to memory management and compatibility issues. By mastering these core technologies, various binary data can be efficiently processed and displayed in web applications.