Skip to content

Instantly share code, notes, and snippets.

@av01d
Created January 20, 2022 13:15
Show Gist options
  • Save av01d/e60f6edf3c5be6cd403eabb3d1f838f4 to your computer and use it in GitHub Desktop.
Save av01d/e60f6edf3c5be6cd403eabb3d1f838f4 to your computer and use it in GitHub Desktop.
Convert base64 string to Uint8Array (one liner)
/**
* One liner to convert a base64 string to a binary Uint8Array
*
* Example:
* const dataURL = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2w....';
* console.log(convertDataURIToBinary(dataURL));
*/
const convertDataURIToBinary = dataURI =>
Uint8Array.from(window.atob(dataURI.replace(/^data[^,]+,/,'')), v => v.charCodeAt(0));
@damianmoore
Copy link

damianmoore commented May 12, 2022

Thanks for writing this alternative @av01d. I was about to switch from https://gist.github.com/borismus/1032746 to this but luckily ran some benchmarks first. For my use case (95MB 40min MP3 file under Firefox 100) this one-liner took 8.45X longer (8751ms vs 1034ms). Same test on Chromium 101, this function was 7.78X longer (12301ms vs 1579ms).

I may have a tinker at some point to optimise speed further but ~1 second is acceptable. Maybe the regex is slowing it down but I feel like the for loop in the original helps to keep the UI responsive too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment