Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Blob from an external image url

I have an file input that i used to get a file and turn it into a blob. Is there anyway I can get an external image url and turn that into a blob? Here is the code I am using to do it with just a file from a <input type="file" />:

//Process the file and resize it.
        function processfile(file) {

            if (!(/image/i).test(file.type)) {
                alert("File " + file.name + " is not an image.");
                return false;
            }

            // read the files
            var reader = new FileReader();
            reader.readAsArrayBuffer(file);

            reader.onload = function (event) {
                // blob stuff
                var blob = new Blob([event.target.result]); // create blob...
                window.URL = window.URL || window.webkitURL;
                var blobURL = window.URL.createObjectURL(blob); // and get it's URL

                // helper Image object
                var image = new Image();
                image.src = blobURL;
                image.onload = function () {

                    for (var x = 0; x < self.ThumbSizes.length; x++) {
                        // have to wait till it's loaded
                        var resized = resizeMe(image, self.ThumbSizes[x]); // send it to canvas
                        var resized_blob = dataURItoBlob(resized);
                        uploadFile(resized_blob, self.ThumbSizes[x].Name);
                    }
                }
            };

Instead of passing a file through I wanted to be able to structure this code to pass a image url and convert it into a blob.

like image 384
anthonypliu Avatar asked Oct 22 '22 10:10

anthonypliu


1 Answers

I hope it helps you. (I didn't run it.)

function processfile(imageURL) {
    var image = new Image();
    var onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width =this.width;
        canvas.height =this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        canvas.toBlob(function(blob) {
            // do stuff with blob
        });
    };

    image.onload = onload;
    image.src = imageURL;
}
like image 135
kechol Avatar answered Oct 30 '22 16:10

kechol