5

我有一个文件输入,用于获取文件并将其转换为 blob。无论如何,我可以获得一个外部图像 url 并将其变成一个 blob 吗?这是我用来仅使用来自 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);
                    }
                }
            };

我希望能够构造此代码以传递图像 url 并将其转换为 blob,而不是通过文件传递。

4

1 回答 1

3

我希望它对你有帮助。(我没有运行它。)

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;
}
于 2014-09-18T17:18:15.573 回答