简体   繁体   English

画布到Blob返回空的Blob对象

[英]Canvas to blob returns empty blob object

I'm trying to convert a canvas element image to blob. 我正在尝试将canvas元素图像转换为blob。 I have tried the below code using canvas-to-blob.min.js and it returns an empty object. 我已经使用canvas-to-blob.min.js尝试了以下代码,它返回一个空对象。 But when converting to data URL it is not empty. 但是,当转换为数据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);

Also I have tried the dataURIToBlob() custom function like this (function not included here) 我也尝试过像这样的dataURIToBlob()自定义函数(此处未包含函数)

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

The result is same emprty object. 结果是相同的Emprty对象。 Please help me to resolve this issue 请帮我解决这个问题

Blob Object's type and size properties are not enumerable, hence, JSON.stringify will ignore their values and return only a string representing an empty object : "{}" . Blob对象的typesize属性不可枚举,因此, JSON.stringify将忽略其值,并且仅返回表示空对象的字符串: "{}"

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

I guess that your blob is well formed, you can send it like this. 我想您的Blob格式正确,您可以像这样发送它。

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM