Essayez ça :
Code
/**
* Convert an image
* to a base64 string
* @param {String} url
* @param {Function} callback
* @param {String} [outputFormat=image/png]
*/
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
Utilisation
convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});
Formats d'entrée pris en charge
- image/png
- image/jpeg
- image/jpg
- image/gif
- image/bmp
- image/tiff
- image/x-icône
- image/svg+xml
- image/webp
- image/xxx
Formats de sortie pris en charge
- image/png
- image/jpeg
- image/webp (chrome)
Démonstration :
http://jsfiddle.net/handtrix/YvQ5y/
Advanced-Code :
https://gist.github.com/HaNdTriX/7704632
Test : type de mime toDataUrl
http://kangax.github.io/jstests/toDataUrl_mime_type_test/
Support des navigateurs (à ce jour)
5 votes
D'où vient votre image ?
5 votes
stackoverflow.com/questions/934012/get-image-data-in-javascript
1 votes
JS et jQ : stackoverflow.com/questions/17710147/
0 votes
idkblogs.com/js/31/Convertir-fichier-image-en-base64-en-javascript