Reputation: 113
I have a response containing an image in png format,but I am unable to display it in react since it is not a url pic of response
does anyone know how I can convert this png into a URL so I can insert it into my src of img tag?
Upvotes: 7
Views: 16085
Reputation: 449
same in my case. "react": "17.0.1", "react-native": "0.64.2",
my response contains png image(no URL, no base64),
I converted my response into base64 as below,
const makeApiRequest = async()=>{
try {
const response = await apiCaller('ProfileImage',{"thisID": "ABCD","thatID": "1234"})
if(response.status === 200){
const dataResponse = await response.blob()
let blob = new Blob([dataResponse], { type: "text/plain" });
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64String = reader.result;
setImageFromAPI(base64String.substr(base64String.indexOf(', ') + 1)); //Setting response to hook
}
}else{
console.log(response.status)
}
} catch (error) {
console.log("components/profile/ProfileTimeline.js:-",error)
}
}
But when I use it in my image tag its shows no image, and i don't know why
<Image source={{uri: `data:image/png;base64,${imagefromAPI}`}} style={{width:100, height:100}} resizeMode="cover" />
Upvotes: 0
Reputation: 1669
This is something I did when I was doing a similar thing in a React project.
The response data will look like this :
With characters that does not look friendly.
The response will now have arrayBuffer in data of the response
The response can then be converted to base64 by
let base64ImageString = Buffer.from(response.data, 'binary').toString('base64')
If you want to display it on an img tag, then prepend data:image/png;base64, to the Base64 string
let srcValue = "data:image/png;base64,"+base64ImageString
But in your case, it seems like you are only getting the file name as a string and not the file itself.
Upvotes: 22
Reputation: 33
Why not treat imege you need as Bese64 string?
If you're able to convert you png image to a Base64 string (server side obviously) you can easily use it in img tag as src attribute value.
Upvotes: 2
Reputation: 16
If you have the image inside your application ( assets folder or whatever ) you could display it like that
<img src={`assets/${coverImage}`}>
Else The image should be sent from the API in the base64 format and then you could simply display it like that.
data = "base64 image"
<img src={`data:image/jpeg;base64,${data}`} />
Upvotes: 0