How to display blob image in react native
Asked Answered
B

3

6

Here is my code:

<Image source={BlobImage} style={{ height: 200, width: null, flex: 1 }} />

Where BlobImage is an image in blob string like thisc916851b-3e53-432d-8d18-3de293776859?offset=0&size=371537.

Edit:

I upload a base64 image to cpanel, and it is automatically cast to Blob. When I fetch the data from cpanel, I get a buffer array and unable to display it. I tried this but it doesn't work

var blob = new Blob([img], {type: "image/png"})
var blobUrl = URL.createObjectURL(blob);

And in render

<Image source={{uri:blobUrl}} style={{ height: 200, width: null, flex: 1 }} />

Where img is the raw data from cpanel and it's a byte array.

This is how I get the data using react-native-photo-upload

<PhotoUpload
    onPhotoSelect={avatar => {
                   if (avatar) {
                       this.setState({
                           imageUrl: avatar
                       });
                   }}}>
Becka answered 19/4, 2018 at 7:37 Comment(0)
S
25

You can convert the blob to base64 from FileReader api and then display it.

Code:

const fileReaderInstance = new FileReader();
 fileReaderInstance.readAsDataURL(blob); 
 fileReaderInstance.onload = () => {
     base64data = fileReaderInstance.result;                
     console.log(base64data);
 }

and display it once you get it as:

<Image source={{uri: base64ImageData}} style={{ height: 200, width: null, flex: 1 }} />
Snob answered 19/4, 2018 at 7:53 Comment(3)
Is this still the best option when using expo?Hildredhildreth
Works as of Nov, 2021.Feudalize
Can you send the full code?Primus
T
0

Maybe you can try something like this

<Image source={{uri: BlobImage}} style={{ height: 200, width: null, flex: 1 }}/>
Thorax answered 19/4, 2018 at 7:39 Comment(0)
A
0

As of 2024, this solution is no longer viable, since uri doesn't render blobs as it was shown. However i've used your question logic to bypass the error on response.data as a blob on the db:

.then((response) => {
            if (response.status === 200 && response.data) {
                const blob = new Blob([response.data]);
                return URL.createObjectURL(blob);
            } 
        })

const response = await getProfilePic({ userId: currentUser?.id || '' });
            if (response) {
                setProfilePicUri(response);
            }

<ImageTouchable alt='Profile Picture' source={{uri: profilePicUri}} />
Apologetics answered 9/5 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.