I'm building an extension on a React app, and I need to fetch an image from an URL to display it to the user. I can only display things in markdown, so I found out I could use raw HTML in markdown to display the image, as long as I have a base64 data URI for the image.
I cannot directly use the image URL because I need to use an Authentication
header with a token, so I first fetch the image and get the data in a variable, then I want to convert that raw data to a base64 URI.
Here's how I fetch the data:
const { isLoading : isLoadingMap, data : dataMap } = useFetch<string>(
'https://api.tessie.com/AN_ID/map?width=430&height=183&zoom=12&marker_size=75&style=light',
{
headers: {
accept: 'application/json',
authorization: 'Bearer ABEARERTOKEN'
}
}
)
The data
variable is a string
, and it is the image data.
I've tried to use atob
on the data but I get "Invalid Character" error. I've also found this solution: Buffer.from(dataMap, 'binary').toString('base64');
on multiple questions but it doesn't seem to produce correct image data either...
In addition, another answer mentioned by Heretic in the comments gives interesting results, but still does not display the image.
Using this code (let's note the use of deprecated btoa
and unescape
):
let map64 = btoa(unescape(encodeURIComponent(dataMap)));
This gives us a base64 string, which when decoded appears to be exactly the image data: .
However, attempting to use the base64 encoded string to display the image (using a data URI) or putting the base64 decoded content in a file both fail and produce invalid image (i.e. can't see/open it)