Home > OS >  Convert blob to image in React Native?
Convert blob to image in React Native?

Time:03-04

I have a blob in aws S3:

https://s3.us-east-2.amazonaws.com/fakedomain.com/2021-12-23T21.888Z-blob

I'm trying to display it within the card

<Card.Cover source={{uri: https://s3.us-east-2.amazonaws.com/fakedomain.com/2021-12-23T21.888Z-blob }} />

When running on Android I get the

 cannot create blob for URL 

The image was originally a jpeg

CodePudding user response:

You have to convert the blob to object URL format first. You could use the code below mate:

const img = document.querySelector('#img');
const s3Url = https://s3.us-east-2.amazonaws.com/fakedomain.com/2021-12-23T21.888Z-blob;

let blob = await fetch(s3Url).blob()
let objectURL = URL.createObjectURL(myBlob);

img.src = objectURL;

CodePudding user response:

So, I went with another route. I store the base64 string from the image picker in s3 instead. From there I fetched it within my Node API and added it to the response so I don't have to reference s3 directly from my native application. Worked like a charm.

so in node it looked like:

async _downloadFile(key) {

    return new Promise((resolve, reject) => {
      const params = {
        Bucket: `BUCKET_NAME`,
        Key: key
      };
      this.s3.getObject(params, (err, data) => {
        if (err) {console.error(err); reject(err);}
        resolve(data.Body.toString());
        console.log(`base64 str has been retrieved!`);
      });

    });
  };

    // END OF FUNCTION BODY BELOW
          resolve(Promise.all(res.rows.map(async (listing) => {
          if (listing.image) {
            const data = await this._downloadFile(listing.image);
            return {
              ...listing,
              image: data,
            };
          }
        })));

I created this utility within my React Native application to serve it up:

export function base64ToImage(base64String:string) {
  return `data:image/jpg;base64,${base64String}`
}
  • Related