'Convert blob to image in React Native?
I have a blob in aws S3:
https://s3.us-east-2.amazonaws.com/fakedomain.com/2021-12-23T21%14%05.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%14%05.888Z-blob }} />
When running on Android I get the
cannot create blob for URL
The image was originally a jpeg
Solution 1:[1]
You have to convert the blob to object URL format first. You could use the code below mate:
const s3Url = https://s3.us-east-2.amazonaws.com/fakedomain.com/2021-12-23T21%14%05.888Z-blob;
let blob = await fetch(s3Url).blob()
let objectURL = URL.createObjectURL(myBlob);
Solution 2:[2]
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}`
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Scott |