Last active
February 25, 2024 15:00
-
-
Save telecran-telecrit/4a392087d5cc241404c83bb32009a25f to your computer and use it in GitHub Desktop.
JS image to data uri
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
function imageToUri (url, callback) { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
var base_image = new Image(); | |
base_image.crossOrigin="anonymous"; | |
base_image.src = url; | |
base_image.onload = function() { | |
canvas.width = base_image.width; | |
canvas.height = base_image.height; | |
ctx.drawImage(base_image, 0, 0); | |
callback(canvas.toDataURL('image/jpeg')); | |
canvas.remove(); | |
} | |
base_image.onerror = function() { | |
try { | |
canvas.remove(); | |
} finally { | |
throw new Error('Error loading image: ' + this.src); | |
} | |
} | |
} | |
// Usage 1.1: | |
imageToUri('https://same.origin.url/pic.png', (uri) => console.log(uri)) | |
// Usage 1.2: | |
function imageToUriPromisified(url) { | |
return new Promise((resolve, reject) => { | |
try { | |
imageToUri(url, (result) => { | |
resolve(result); | |
}); | |
} catch (e12) { | |
reject(e12); | |
} | |
}); | |
} | |
async function convertImage() { | |
imageUrl = 'https://same.origin.url/pic.png'; | |
result = await imageToUriPromisified(imageUrl); | |
console.log(result); | |
}; | |
convertImage() |
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
function imageToUri (url) { | |
return new Promise((resolve, reject) => { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
var base_image = new Image(); | |
base_image.crossOrigin = "anonymous"; | |
base_image.src = url; | |
base_image.onload = function () { | |
canvas.width = base_image.width; | |
canvas.height = base_image.height; | |
ctx.drawImage(base_image, 0, 0); | |
resolve(canvas.toDataURL('image/jpeg')); | |
canvas.remove(); | |
}; | |
base_image.onerror = function (err) { | |
reject(err); | |
}; | |
}); | |
} | |
// Usage 2: | |
async function convertImage() { | |
imageUrl = 'https://same.origin.url/pic.png'; | |
result = await imageToUri(imageUrl); | |
console.log(result); | |
}; | |
convertImage() |
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
function imageToUriWithAjax (url, callback) { | |
var IE=function(){var ret,isTheBrowser,actualVersion,jscriptMap,jscriptVersion;isTheBrowser=false;jscriptMap={"5.5":5.5,"5.6":6,"5.7":7,"5.8":8,"9":9,"10":10}; | |
//if (window.Function) { // jscriptVersion = new Function("/*@cc_on return @_jscript_version; @*/")(); //} else { // jscriptVersion = eval("(function anonymous() { return /*@cc_on return @_jscript_version; @*/})()"); //} | |
var jscriptVersion/*@cc_on=@_jscript_version@*/;if(jscriptVersion!==undefined){isTheBrowser=true;actualVersion=jscriptMap[jscriptVersion]}else if(/msie/.test(navigator.userAgent.toLowerCase())){isTheBrowser=true;actualVersion=11}else{isTheBrowser=false}ret={isTheBrowser:isTheBrowser,actualVersion:actualVersion};return ret}(); | |
var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Base64={_keyStr:b64,encode:function r(e){var t,o,a,h,d,c,n,f="",C=0;for(e=Base64._utf8_encode(e);C<e.length;)t=e.charCodeAt(C++),o=e.charCodeAt(C++),a=e.charCodeAt(C++),h=t>>2,d=(3&t)<<4|o>>4,c=(15&o)<<2|a>>6,n=63&a,isNaN(o)?c=n=64:isNaN(a)&&(n=64),f=f+this._keyStr.charAt(h)+this._keyStr.charAt(d)+this._keyStr.charAt(c)+this._keyStr.charAt(n);return f},decode:function r(e){var t,o,a,h,d,c,n,f="",C=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");C<e.length;)h=this._keyStr.indexOf(e.charAt(C++)),d=this._keyStr.indexOf(e.charAt(C++)),c=this._keyStr.indexOf(e.charAt(C++)),n=this._keyStr.indexOf(e.charAt(C++)),t=h<<2|d>>4,o=(15&d)<<4|c>>2,a=(3&c)<<6|n,f+=String.fromCharCode(t),64!=c&&(f+=String.fromCharCode(o)),64!=n&&(f+=String.fromCharCode(a));return Base64._utf8_decode(f)},_utf8_encode:function r(e){e=e.replace(/\r\n/g,"\n");for(var t="",o=0;o<e.length;o++){var a=e.charCodeAt(o);a<128?t+=String.fromCharCode(a):a>127&&a<2048?(t+=String.fromCharCode(a>>6|192),t+=String.fromCharCode(63&a|128)):(t+=String.fromCharCode(a>>12|224),t+=String.fromCharCode(a>>6&63|128),t+=String.fromCharCode(63&a|128))}return t},_utf8_decode:function r(e){for(var t="",o=0,a=c1=c2=0;o<e.length;)(a=e.charCodeAt(o))<128?(t+=String.fromCharCode(a),o++):a>191&&a<224?(t+=String.fromCharCode((31&a)<<6|63&(c2=e.charCodeAt(o+1))),o+=2):(t+=String.fromCharCode((15&a)<<12|(63&(c2=e.charCodeAt(o+1)))<<6|63&(c3=e.charCodeAt(o+2))),o+=3);return t},btoa:function r(e){e=String(e);for(var t,o,a,h,d="",c=0,n=e.length%3;c<e.length;){if((o=e.charCodeAt(c++))>255||(a=e.charCodeAt(c++))>255||(h=e.charCodeAt(c++))>255)throw TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");t=o<<16|a<<8|h,d+=b64.charAt(t>>18&63)+b64.charAt(t>>12&63)+b64.charAt(t>>6&63)+b64.charAt(63&t)}return n?d.slice(0,n-3)+"===".substring(n):d},atob:function r(e){if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!b64re.test(e))throw TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");e+="==".slice(2-(3&e.length));for(var t,o,a,h="",d=0;d<e.length;)t=b64.indexOf(e.charAt(d++))<<18|b64.indexOf(e.charAt(d++))<<12|(o=b64.indexOf(e.charAt(d++)))<<6|(a=b64.indexOf(e.charAt(d++))),h+=64===o?String.fromCharCode(t>>16&255):64===a?String.fromCharCode(t>>16&255,t>>8&255):String.fromCharCode(t>>16&255,t>>8&255,255&t);return h}}; | |
var xmlHTTP = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); | |
xmlHTTP.open('GET', url, true); | |
xmlHTTP.responseType = 'arraybuffer'; | |
if (IE.isTheBrowser && IE.actualVersion < 9) { | |
xmlHTTP.onreadystatechange = function(e) { | |
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) { | |
var arr = new Uint8Array(this.response); | |
var raw = String.fromCharCode.apply(null, arr); | |
var b64img = Base64.btoa(raw); | |
var dataURL="data:image/png;base64," + b64img; | |
callback(dataURL); | |
} | |
}; | |
} else { | |
xmlHTTP.onload = function(e) { | |
var arr = new Uint8Array(this.response); | |
var raw = String.fromCharCode.apply(null, arr); | |
var b64img = Base64.btoa(raw); | |
var dataURL="data:image/png;base64," + b64img; | |
callback(dataURL); | |
}; | |
} | |
xmlHTTP.onerror = function () { | |
try { | |
canvas.remove(); | |
} catch (e3) { | |
} | |
throw new Error('Error loading image by ajax: ' + url); | |
}; | |
xmlHTTP.send(); | |
} | |
// Usage 3: | |
imageToUriWithAjax('https://same.origin.url/pic.png', function next (uri) { | |
console.log(uri); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment