2

I am trying to show an image gotten from a server in a React Native app. What I am getting in the response look like this:

enter image description here

I tried to build a Buffer object using buffer and then parse to 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)

This returns a base64 image but it doesn't show using the React Native Image component

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

I didn't found how to handle images with this structure (a buffer as a numbers array) on React Native. I was thinking that maybe it is a way to do this without the library mentioned or without parse the buffer to a base64 but I don't know.

Thank you

Andres Pino
  • 155
  • 3
  • 9

1 Answers1

6

I dont see any width and height provided to your image, this is the first common issue I faced and wasted my whole day, after providing the width and height, even if the image is not shown see the below solution

I have used this function to convert BufferArray into Base64

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

I have utilized the above function like this

              <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
                }}
              />
Shahbaz Shaikh
  • 204
  • 2
  • 8