Created
November 7, 2015 22:17
-
-
Save oliyh/db3d1a582aefe6d8fee9 to your computer and use it in GitHub Desktop.
Convert an image url to a data URI without canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hard won knowledge from http://stackoverflow.com/questions/20035615/using-raw-image-data-from-ajax-request-for-data-uri | |
var xmlHTTP = xhr.XMLHttpRequest(); | |
xmlHTTP.open('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; | |
}; | |
xmlHTTP.send(); |
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
@CalebMacdonaldBlack seems to be having CORS error in XHR.
Any comments on this ??
@CalebMacdonaldBlack seems to be having CORS error in XHR.
Any comments on this ??
same problem
@CalebMacdonaldBlack
thanks a lot for this solution
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]}
(rf/reg-event-db
::my-handler
(fn [db [_ response]]
(assoc db :thing (->> response
(js/Uint8Array.)
(js/String.fromCharCode.apply nil)
(js/btoa)
(str "data:image/png;base64,")))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/a/55738466/4705339