0

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

1 Answer 1

1

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:

fiddle

Test: toDataUrl mime type

http://kangax.github.io/jstests/toDataUrl_mime_type_test/

Browser Support (so far I know)

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).

Sign up to request clarification or add additional context in comments.

5 Comments

i test this solution but the event onload don't work when i set the src attribut....
But i will try with fileReader and back
Have you see the fiddle?
yes i have but i almost solved my problem :) i inpired of the convertImageToDataURI function :) but now it's my base64 it's not good :/
Perfect ;) have you got another stuck?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.