如何在反应中将blob字符串转换为图像

发布于 2025-01-09 17:21:43 字数 1266 浏览 0 评论 0原文

我正在开发一个反应程序,从后端获取图像并将其显示在前端。 API 调用工作正常,我可以在测试 API 时在邮递员中获得图像预览。但我无法在前端将其转换为图像。

以下是我从后端收到的响应:

{data: '����\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00��\x02(ICC_PROFILE\x00\x01\x01\x00\x00\x02\x18\x00\x00\x00\x00\x02\x10\x00\x00…��M�M�2(݃\x04�#�ɤ�j7�\x02�W\x137�1x�-��.b[�Y���7%���];�H��', status: 200, statusText: '', headers: {…}, config: {…}, …}

这里的数据是图像的字符串版本,我需要将其转换为前端的图像。下面是我的前端代码:

import './App.css';
import axios from 'axios';
import React, {useState, useEffect} from 'react';

function App() {
  const[imageUrl, setImageUrl] = useState('')

  useEffect(() => {
    axios.get('http://localhost:8080/userImage/[email protected]/download/', {
      headers: {
      }
    })
    .then(response => {
      console.log(response)
      const url = URL.createObjectURL(response.data);
      setImageUrl(response.data)
      console.log(url)
    })
    .catch(err => {
      console.log(err)
    })
  },[])

  return (
    <div className="App">
      <img src={imageUrl} alt="Image Placeholder"/>
    </div>
  );
}

export default App;

I'm working on a react program to get an image from the backend and display it in the frontend. The API call is working fine and I'm able to get the image preview in the postman while testing the API. But I couldn't convert it into an image in the front end.

Below is the response I received from the backend:

{data: '����\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00��\x02(ICC_PROFILE\x00\x01\x01\x00\x00\x02\x18\x00\x00\x00\x00\x02\x10\x00\x00…��M�M�2(݃\x04�#�ɤ�j7�\x02�W\x137�1x�-��.b[�Y���7%���];�H��', status: 200, statusText: '', headers: {…}, config: {…}, …}

Here data is the string version of the image and I need to convert it to an image in the frontend. Below is my frontend code:

import './App.css';
import axios from 'axios';
import React, {useState, useEffect} from 'react';

function App() {
  const[imageUrl, setImageUrl] = useState('')

  useEffect(() => {
    axios.get('http://localhost:8080/userImage/[email protected]/download/', {
      headers: {
      }
    })
    .then(response => {
      console.log(response)
      const url = URL.createObjectURL(response.data);
      setImageUrl(response.data)
      console.log(url)
    })
    .catch(err => {
      console.log(err)
    })
  },[])

  return (
    <div className="App">
      <img src={imageUrl} alt="Image Placeholder"/>
    </div>
  );
}

export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仙气飘飘 2025-01-16 17:21:43

我不确定您是否使用响应类型。您需要将响应类型指定为 blob

return axios
    .get(url, {
      responseType: 'blob'
    }).then()

I am not sure if you are using response type or not. You need to specify response type as blob

return axios
    .get(url, {
      responseType: 'blob'
    }).then()
娇妻 2025-01-16 17:21:43

对于字符串,

<img src={`data:image;base64,${img}`} alt="img" />

另一种方式用于文件和 BLOB 等对象

const imgUrl = URL.createObjectURL(img);

for string

<img src={`data:image;base64,${img}`} alt="img" />

another way for Objects like File and BLOB

const imgUrl = URL.createObjectURL(img);
一场春暖 2025-01-16 17:21:43

您似乎正在将一个字符串传递给 URL.createObjectURL()。根据 docs 您应该传递目的;更具体地说,是 File、Blob 或 MediaSource 对象。

我花了一些时间想出了一个解决方案,虽然我怀疑它不是最有效的,但它至少可以工作

在后端确保发送一个base64字符串:

const fs = require('fs');
const path = require('path');

app.get('/photo-test', async (req, res) => {
  let base64 = await fs.readFileSync(path.join(__dirname, "photos", "testPhoto.png"), 'base64'); //change the path to your specific photo
  res.status(200).send(base64).end();
});

然后在react中将base64字符串转换为一个新的Blob并将其用于URL.createOjectURL([新 Blob])

const [imageUrl, setImageUrl] = useState('')

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

useEffect(() => {
    axios.get('http://localhost:5000/photo-test', {
        headers: {
        }
    })
        .then(response => {
            const blob = base64toBlob(response.data);
            const url = URL.createObjectURL(blob);
            setImageUrl(url)
        })
        .catch(err => {
            console.log(err)
        })
}, [])

return (
    <div className="App">
        <img src={imageUrl} alt="Image Placeholder" />
    </div>

请注意取自this堆栈溢出的新函数base64toBlob邮政。

It seems you are passing a string to URL.createObjectURL(). According to the docs you should instead be passing an object; more specifically either a File, Blob or MediaSource object.

I spent some time coming up with a solution and though I suspect it is not the most efficient it does at least work

On the backend make sure to send a base64 string:

const fs = require('fs');
const path = require('path');

app.get('/photo-test', async (req, res) => {
  let base64 = await fs.readFileSync(path.join(__dirname, "photos", "testPhoto.png"), 'base64'); //change the path to your specific photo
  res.status(200).send(base64).end();
});

Then in react convert the base64 string into a new Blob and use that for URL.createOjectURL([new Blob]).

const [imageUrl, setImageUrl] = useState('')

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

useEffect(() => {
    axios.get('http://localhost:5000/photo-test', {
        headers: {
        }
    })
        .then(response => {
            const blob = base64toBlob(response.data);
            const url = URL.createObjectURL(blob);
            setImageUrl(url)
        })
        .catch(err => {
            console.log(err)
        })
}, [])

return (
    <div className="App">
        <img src={imageUrl} alt="Image Placeholder" />
    </div>

Note the new function base64toBlob taken from this stack overflow post.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文