Home > Back-end >  convert base64 string to usable URL
convert base64 string to usable URL

Time:05-19

I have a string that was made using toDataURL() on my HTML canvas, creating an image. I'd like to be able to encode / decode that string so it can be used with window.open(string)

string looks like

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAOfCAYAAAApbd6bAAAgAElEQVR4Xuzdfaxt6V0X8OHct5nplEHQUFobiJEWakwNiRKjmIqJBQShCS...

CodePudding user response:

This is what ended up working for me, with src being the base64 string

  const openImg = () => {
    const base64ImageData = src;
    const contentType = 'image/png';
    const byteCharacters = atob(base64ImageData.substr(`data:${contentType};base64,`.length));
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset  = 1024) {
      const slice = byteCharacters.slice(offset, offset   1024);

      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i  ) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);

      byteArrays.push(byteArray);
    }
    const blob = new Blob(byteArrays, { type: contentType });
    const blobUrl = URL.createObjectURL(blob);

    window.open(blobUrl, '_blank');
  }
  • Related