在 React Native 上将缓冲区图像解析为 base64

Parse buffer image to base64 on React Native

我正在尝试在 React Native 应用程序中显示从服务器获取的图像。我在响应中得到的内容如下所示:

我尝试使用 buffer 构建一个 Buffer 对象,然后解析为 base64

const imageBuffer = Buffer.from(JSON.stringify(res.data)) // This res.data is the whole object, including the type "Buffer" and the data array
const imageBase64 = imageBuffer.toString('base64')
setImage(imageBase64)

此 returns base64 图片,但使用 React Native Image 组件不显示

<Image source={{ uri: `data:image/jpeg;base64,${image}` }} />

我没有找到如何在 React Native 上使用这种结构(作为数字数组的缓冲区)处理图像。我在想,也许这是一种在不提及库或不将缓冲区解析为 base64 的情况下执行此操作的方法,但我不知道。

谢谢

我没有看到为您的图片提供任何宽度和高度,这是我遇到的第一个常见问题并且浪费了我一整天的时间,在提供宽度和高度之后,即使没有显示图片也请参阅以下解决方案

我用这个函数把BufferArray转成Base64

来源link

  arrayBufferToBase64 = buffer => {
    let binary = '';
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  };

上面的功能我是这样使用的

              <Image
                style={{
                  width: 200,
                  height: 200,
                  resizeMode: 'cover',
                  backgroundColor: 'red',
                }}
                source={{
                  uri:
                    'data:image/jpeg;base64,' +
                    this.arrayBufferToBase64(data.data), //data.data in your case
                }}
              />