0

I want to save facebook profile image URL to file object I tried to convert it to base64 then convert it to file object but i want file object outside the function maybe it some sort of stupid question but any help? following what i tried

var imgUrl = 'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png';
var convertImgToDataURLviaCanvas = function(url, callback) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL();
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}

convertImgToDataURLviaCanvas(imgUrl, function(base64_data) {
    var byteString = atob(base64_data.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: 'image/jpeg'
    });
    var file = new File([blob], "images.jpg");
    console.log(file)
});
Umer bin Siddique
  • 460
  • 1
  • 4
  • 13
  • You can directly convert to blob by using canvas.toBlob function. Then if you still need file you can check this https://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript – Shyam Babu Mar 16 '18 at 08:03

1 Answers1

0

You can use global variable and assign file object to that variable inside your function.

basically split var file = new File([blob], "images.jpg");

into

var file = null; //outside convertImgToDataURLviaCanvas

file = new File([blob], "images.jpg"); //inside convertImgToDataURLviaCanvas

Tapas
  • 1,123
  • 8
  • 16