Start your developer blog today!
Email me

How to Display JFIF Binary Image Data in JavaScript

Aug 8, 2020 1 min read

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.

  .then(resp => resp.data.blob())
  .then(blob => {
    const url = URL.createObjectURL(blob);
    document.getElementById("preview").src = url;

More JavaScript Articles