js: A simple example of converting a picture connection to base64 format
- 2021-07-09 07:13:36
- OfStack
We write the contents of the image file directly into the HTML file, which has the advantage of saving 1 HTTP request. The downside is that browsers don't cache such images. Now we provide an js:
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});