Skip to content

Instantly share code, notes, and snippets.

Created November 7, 2015 22:17
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save oliyh/db3d1a582aefe6d8fee9 to your computer and use it in GitHub Desktop.
Convert an image url to a data URI without canvas
// hard won knowledge from
var xmlHTTP = xhr.XMLHttpRequest();'GET', url, true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = base64.encode(raw);
var dataURL="data:image/png;base64," + b64;
Copy link

FLasH3r commented Jul 6, 2018

Uncaught ReferenceError: xhr is not defined

Copy link


var xmlHTTP = new XMLHttpRequest();

That's all you need.

Copy link

var b64 = btoa(raw);

Copy link

This solutions works for both <img> and SVG's <image>.

Copy link

How do I access the dataUrl which stores the base64 string?

Copy link

sentiasa commented Apr 18, 2019

Copy link

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
  };'GET', url);
  xhr.responseType = 'blob';

toDataURL('', function(dataUrl) {
  console.log('RESULT:', dataUrl)

Copy link

rohitchatla commented Aug 2, 2020

@CalebMacdonaldBlack seems to be having CORS error in XHR.
Any comments on this ??

Copy link

ozzpy commented Aug 9, 2020

@CalebMacdonaldBlack seems to be having CORS error in XHR.
Any comments on this ??

same problem

Copy link

thanks a lot for this solution

Copy link

remyrd commented Oct 19, 2021

Rewrote this into re-frame / ajax-cljs

(require '[ajax.protocols :as pr])

;; effecting with re-frame-http-fx
{:http-xhrio {,,,
              :response-format {:content-type "image/png"
                                :description "PNG image"
                                :read pr/-body
                                :type :arraybuffer}
              :on-success [::my-handler]}

  (fn [db [_ response]]
    (assoc db :thing (->> response
                          (js/String.fromCharCode.apply nil)
                          (str "data:image/png;base64,")))))

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