画布到blob返回空blob对象

时间:2016-08-08 05:25:22

标签: javascript html5 canvas blob

我试图将画布元素图像转换为blob。我使用canvas-to-blob.min.js尝试了下面的代码,它返回一个空对象。但是,当转换为数据URL时,它不是空的。

var file = getFile();
var reader = new FileReader();
  reader.onload = function (e) {

   var img = new Image();

   img.onload = function () {

     var canvas = document.createElement("canvas");
         canvas.height = height;
         canvas.width = width;
         var ctx=canvas.getContext("2d"); 
        ctx.drawImage(img,0,0,width,height);                        

    var data_URL = canvas.toDataURL('image/png');   /* Returns correct data URL */

        if (canvas.toBlob) {
                         canvas.toBlob(
                                 function (blob) {

                                           console.log(JSON.stringify(blob)) /* Return empty */
                                            var formData = new FormData();
                                            formData.append('file', blob, fileName);
                                            /* ... */
                                        },
                                        'image/jpeg'
                                    );
                                }


        }

     img.src = this.result;

   }

 reader.readAsDataURL(file);

我也试过像这样的dataURIToBlob()自定义函数(这里没有包含这个函数)

var data_URL = canvas.toDataURL('image/png');
var blob = dataURIToBlob(data_URL);
console,log(JSON.stringify(blob))   /* returns empty object */

结果是同一个emprty对象。请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

Blob对象的typesize属性不可枚举,因此JSON.stringify将忽略其值并仅返回表示空对象的字符串:"{}"

var blob = new Blob(['hello world'], {type:'text/plain'});

console.log(JSON.stringify(blob));
console.log(blob);

我猜你的blob形成得很好,你可以像这样发送它。

答案 1 :(得分:-1)

ResizeImage(file) {
    // Read in file
    var self=this;
    var file = file;

    var image = new Image();
    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {

            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 128,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = self.dataURItoBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
                self.setState({Thumb:resizedImage});
                console.log(resizedImage);
                console.log(self.state);
            }
            image.src = readerEvent.target.result;


        }
        reader.readAsDataURL(file);
    }


}
dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer
    var ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ab], {type: mimeString});
    return blob;

}