javascript 如何获取和显示blob图像

uxhixvfz  于 2023-05-16  发布在  Java
关注(0)|答案(2)|浏览(280)

我试图将图像保存到indexeddb,然后在react应用程序中获取并显示它们。我的方法是将图像转换为blob,并将blob url保存到indexeddb,然后在需要显示时,获取blob url并将图像url设置为. src。
我如何创建blob

fetch(imgurl, {
                mode: 'no-cors',
                method: "get",
                headers: {
                     "Content-Type": "application/json"
                } 
             }) 
            .then(response => response.blob())
            .then(async images => {
               
                    var blob_url = URL.createObjectURL(images)
                  
                    var blobA = blob_url.replace("blob:","") 
                    var blobB = blobA.replace('"','')

这是bloburl blob:http://localhost:3000/d 7a 55 f39-b496- 476 b-8 c3 c-857874 bd 107 c
然后删除blob:并将此URL保存在indexeddb中以便在需要时获取http://localhost:3000/d 7a 55 f39-b496 - 476 b-8 c3 c-857874 bd 107 c
这是我需要使用斑点图像的地方

import React from "react";
import { Row, Col, Container, Image } from 'react-bootstrap';

   
function Item({ item }) { 
    const imgurl = item.productimg
    fetch(imgurl)
        .then(res => res.blob()) // Gets the response and returns it as a blob
        .then(async blob => {
            const test = await blobToImage(blob)  
            console.log("image test",test)
        
            let objectURL = URL.createObjectURL(blob);
           let myImage = document.getElementById('myImg')
           myImage.src = objectURL;
            
        });
       
    return (
        <div className="item" id={item.id}>

            <Row>
                <Col> 
                <Image  id="myImg" width="50" height="58" rounded />

                </Col>
                <Col xs={6}>
                    <div className="item-info">
                        <p>{item.name}</p>
                    </div>
                </Col>
                <Col>3 of 3</Col>
            </Row>
           

            <div className="item-actions">
                <button className="btn-remove">X</button>
            </div>
        </div>
    );
}

export default Item;

项包含所有productdata,包括保存的blob url。问题是图像没有显示,我不知道为什么。
我可能做错了什么,我如何显示图像

sauutmhj

sauutmhj1#

不要修改Blob的URL。

当您从Blob的URL字符串中取出blob:部分时,浏览器不再知道您正在引用Blob。相反,在使用URL.createObjectURL创建URL后,请尝试将其单独保留。
最重要的是,当组件与外部资源同步时(如获取数据),您应该使用React's useEffect hook

React示例

你可以view this example live at StackBlitz

function Item({ item }) {
  const imgURL = item.productimg;
  const [blobURL, setBlobURL] = React.useState(null);

  React.useEffect(() => {
    const controller = new AbortController(); // https://developer.mozilla.org/en-US/docs/Web/API/AbortController
    const signal = controller.signal;
    fetch(imgURL, { signal })
      .then((res) => res.blob()) // Get the response and return it as a blob
      .then((blob) => { // Create a URL to the blob and use it without modifying it.
        setBlobURL(URL.createObjectURL(blob));
      })
      .catch((error) => { // Error handling here
        console.error(error);
      });

    // Cancel the fetch request on any dependency change
    return () => controller.abort();
  }, [imgURL]);

  return (
    <div className="item" id={item.id}>
      <Row>
        <Col>
          {blobURL ? <Image src={blobURL} id="myImg" width="50" height="58" rounded /> : <p>Loading...</p>}
        </Col>
        <Col xs={6}>
          <div className="item-info">
            <p>{item.name}</p>
          </div>
        </Col>
        <Col>3 of 3</Col>
      </Row>

      <div className="item-actions">
        <button className="btn-remove">X</button>
      </div>
    </div>
  );
}

纯JavaScript示例

const imgURL = "https://cdn62.picsart.com/182788826000202.jpg?type=webp&to=crop&r=256"
fetch(imgURL)
  .then(response => response.blob())
  .then(blob => {
    document.getElementById('my-img').src = URL.createObjectURL(blob)
  })
<img id="my-img" />

祝你好运

相关问题