5

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.

anthonypliu
  • 12,179
  • 28
  • 92
  • 154
  • 1
    Is this the type of solution you are looking for? http://stackoverflow.com/questions/934012/get-image-data-in-javascript – Nate May 07 '13 at 00:33

1 Answers1

3

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;
}
kechol
  • 1,554
  • 2
  • 9
  • 18
  • 4
    canvas.toBlob is not supported on major browsers like chrome but you can use this polyfill https://github.com/blueimp/JavaScript-Canvas-to-Blob – Safareli Sep 28 '14 at 12:50
  • 1
    With that solutions you'll get ```Uncaught SecurityError: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.``` in case if server send you image without CORS allow headers. – Pavlo Sadovyi Jul 16 '19 at 09:10