0

I am trying to render an image on my page by calling an API from a useEffect hook. The service returns a blob, which gets saved in a state. Finally, the state variable is called from an image src attribute.

So far I have tried using the URL.createObjectURL() method in the image src's attribute, but I get the following error.

<img src={URL.createObjectURL(blob)} alt="test image" />

error in console

Also I tried converting the blob's string into a blob, then passing it into the URL.createObjectURL() method. The result is an image with an src attribute of blob:https://i86fqf.csb.app/fcab2185-c1b2-4fe7-9c9b-8ca3c56a4467 but the image does not loads.

// Other imports ...
import response from "./response";

export default function App() {
  const [imageBlob, setImageBlob] = useState(response);
  const blob = new Blob([imageBlob.items[0].image.$content], {
    type: "image/jpeg"
  });
  const imageURL = URL.createObjectURL(blob);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <img src={imageURL} alt="img" />
    </div>
  );
}

image not loading

Any idea what I am missing? You can find a code example here https://codesandbox.io/s/image-blob-not-loading-i86fqf

1 Answer 1

1

The '$content' is the base64 string, and if you want to create blob from this, you can study the post here: Creating a BLOB from a Base64 string in JavaScript

Or you can simply add "data:image/png;base64," to make base64 work as src.

  const base64 = `data:image/png;base64,${imageBlob.items[0].image.$content}`;
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <img src={base64} alt="img" />
    </div>
  );
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.