Search code examples
javascriptbase64service-workercloudflare

javascript fetch an image and create base64


I'm using CloudFlare service workers and I want to fetch an image and then generate a base64 representation of it.

So something like this:

const res = await fetch('https://cdn.cnn.com/cnnnext/dam/assets/211010073527-tyson-fury-exlarge-169.jpg')
  const blob = await res.blob();
  
  console.log(blob)
  console.log(btoa(blob))

this of course doesn't work, any ideas how to get this resolved?


Solution

  • complete worker script with cloudflare using btoa

    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    const imageUrl =
      'https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/' +
      'Cat_playing_with_a_lizard.jpg/1200px-Cat_playing_with_a_lizard.jpg';
    
    function base64Encode (buf) {
      let string = '';
      (new Uint8Array(buf)).forEach(
          (byte) => { string += String.fromCharCode(byte) }
        )
      return btoa(string)
    }
    
    function base64Decode (string) {
      string = atob(string);
      const
        length = string.length,
        buf = new ArrayBuffer(length),
        bufView = new Uint8Array(buf);
      for (var i = 0; i < length; i++) { bufView[i] = string.charCodeAt(i) }
      return buf
    }
    
    async function handleRequest(request) {
      const
        upstreamResponse = await fetch(imageUrl),
        text = base64Encode(await upstreamResponse.arrayBuffer()),
        bin = base64Decode(text);
      
      return new Response(bin, {status: 200, headers: {
          'Content-type': upstreamResponse.headers.get('Content-type')
        }})
    }
    

    can refer this discussion as well