javascript: image blob

2020-10-15

 | 

~2 min read

 | 

223 words

Recently I was working with an API that was returning binary data of images. I wanted to render them to a page which led me to discover the static method createObjectURL.

The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

processBlobs.jsx
import React, { useEffect, useState } from "react";

export default function App() {
  const [imgSrc, setImgSrc] = useState<Blob>();

  const target: string = "https://picsum.photos/200/300"; // fetch a random photo from lorem picsum

  useEffect(() => {
    fetch(target)
      .then(res => res.blob())
      .then(res => {
        setImgSrc(URL.createObjectURL(res));
        console.log(res);
      })
  }, []);

  return (
    <div className="App">
      <img src={imgSrc} />
    </div>
  );
}

in this case, the API is quite simple because the res from the API call has already been converted to a Blob, so we can simply pass it into URL.createObjectURL(). If we only had the binary data, we could instantiate a new Blob like so:

URL.createObjectURL(new Blob([res], { type: "image/jpeg" }))

Blobs remain a bit of a mystery to me. There’s so much left to learn and ways to work with them. Creating an Object URL for them, however, makes it slightly easier for the future.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!