简体   繁体   中英

React JS: rendering an image from blob

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" />

控制台中的错误

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>
  );
}

图片未加载

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

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>
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM