简体   繁体   中英

Javascript Base64 Remote File

Is it possible to base64 encode a file with Javascript directly from a remote URL? For example, if I wanted to base64 encode the google logo within my app from https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png with only javascript, can it be done?

I found a viable solution using an html5 canvas and jquery - jsfiddle copied here. I'll probably go this route:

https://jsfiddle.net/bu25sosf/1/

function convertImgToBase64(url, callback, outputFormat) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}


$('#img2b64').submit(function (event) {
    var imageUrl = $(this).find('input[name=url]').val();
    console.log('imageUrl', imageUrl);
    convertImgToBase64(imageUrl, function (base64Img) {
        $('.output')
            .find('textarea')
            .val(base64Img)
            .end()
            .find('a')
            .attr('href', base64Img)
            .text(base64Img)
            .end()
            .find('img')
            .attr('src', base64Img);
    });

    event.preventDefault();
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM