-1

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: Screenshot of a base64 decoder.

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)

Gugu72
  • 2,052
  • 13
  • 35
  • Unfortunately no, but I'm going to update my question with the interesting result when using the most upvoted answer from that question – Gugu72 Aug 16 '23 at 20:52
  • Note that there are eight other answers on that question, some of which don't even mention `btoa`, including [this one](https://stackoverflow.com/a/29006759/215552)... – Heretic Monkey Aug 16 '23 at 21:08
  • 1
    Don't use a data: URL at all (you almost never need one). Instead fetch your resource as a Blob and then create a blob: URL from it. I'm no expert in reactjs but it seems all it takes is to pass `responseType: "blob"` in your request init: https://codesandbox.io/s/usefetch-use-http-todo-list-app-managed-state-forked-gcyhz8 – Kaiido Aug 17 '23 at 02:47
  • @Kaiido blob didn't work, but I found another answer that helped me fix my issue! https://stackoverflow.com/a/75269953/12134355 – Gugu72 Aug 17 '23 at 07:59

0 Answers0