How to Display JFIF Binary Image Data in JavaScript đ[All Method]ī¸
![How to Display JFIF Binary Image Data in JavaScript đ[All Method]ī¸](https://howisguide.com/wp-content/uploads/2022/02/How-to-Display-JFIF-Binary-Image-Data-in-JavaScript-All-Method.png)
Are you looking for an easy guide on How to Display JFIF Binary Image Data in JavaScript. If you get stuck or have questions at any point,simply comment below.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Display JFIF Binary Image Data in JavaScript. Question: What is causing this error and what can be done to fix it? Answer: Check out this blog for a solution to your problem.
Earlier, I was obtaining images from an API that returned binary data. I wanted to load the returned image into my <img>
element below.
<img id="preview" src="">
After reading through the response from the API, I finally realized that I was getting a JFIF
(JPEG File Interchange Format) response, a very common format for transmitting/storing photos.
I could tell since the binary data began with this:
īŋŊīŋŊīŋŊīŋŊJFIFīŋŊīŋŊīŋŊ īŋŊīŋŊīŋŊ
Some great detective work, right?
In order to display this image from an axios
call, I set the responseType
to blob
and ran the data through URL.createObjectURL()
.
axios.get(API_URL, { responseType: "blob" }).then(resp => {
const url = URL.createObjectURL(resp.data);
document.getElementById("preview").src = url;
});
We can do the same thing using the fetch
API.
fetch(API_URL)
.then(resp => resp.data.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
document.getElementById("preview").src = url;
});
Revise the code and make it more robust with proper test case and check an error there before implementing into a production environment.
If you need help at any point, please send me a message and I will do my best to assist you.