简体   繁体   English

React JS:从 blob 渲染图像

[英]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.我正在尝试通过从useEffect挂钩调用 API 在我的页面上呈现图像。 The service returns a blob, which gets saved in a state.该服务返回一个 blob,该 blob 保存在 state 中。 Finally, the state variable is called from an image src attribute.最后,从图像 src 属性调用 state 变量。

So far I have tried using the URL.createObjectURL() method in the image src's attribute, but I get the following error.到目前为止,我已经尝试在图像 src 的属性中使用URL.createObjectURL()方法,但出现以下错误。

<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.我还尝试将 blob 的字符串转换为 blob,然后将其传递给URL.createObjectURL()方法。 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.结果是一个 src 属性为blob:https://i86fqf.csb.app/fcab2185-c1b2-4fe7-9c9b-8ca3c56a4467的图像,但图像未加载。

// 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您可以在此处找到代码示例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 '$content' 是 base64 字符串,如果您想从中创建 blob,可以在此处研究帖子: 从 Z686155AF75A60A0F6E9D80C1F7EDD3E 中的 Base64 字符串创建 BLOB

Or you can simply add "data:image/png;base64," to make base64 work as src.或者您可以简单地添加“data:image/png;base64”,使 base64 作为 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>
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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