i have a problem to convert an image to base64 with the library base64 of angularjs.
see my function :
var img = new Image();
img.src = conf.storeUrl + '/' +$scope.fRoot.name + $scope.getFileWay() + value.name;
var base64Img = base64.encode(img);
the url of the image is good and the image has been created but the base64Img is empty... i don't understand why.... Some one have a idea ?
thank in advance
Try this:
/**
* Convert image
* to a base64 data uri
* @param {String} url
* @param {Function} callback
* @param {String} [outputFormat=image/png]
*/
function convertImageToDataURI(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
Usage
convertImageToDataURI('ImageLink', function(base64Decoded){
// Base64DataURI
});
Supported input formats
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats
image/png,image/jpeg,image/webp (chrome)
Demo:
Test: toDataUrl mime type
http://kangax.github.io/jstests/toDataUrl_mime_type_test/
Browser Support (so far I know)
IE10 (IE10 just works with same origin images)
Images from the local file system
If you want to convert images from the users file system you need to take a different approach. Use the FileReader API (Check out this fiddle ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.