【问题标题】:Canvas to blob returns empty blob object画布到 blob 返回空 blob 对象
【发布时间】:2016-12-13 19:01:45
【问题描述】:

我正在尝试将画布元素图像转换为 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 */

结果是相同的空对象。请帮我解决这个问题

【问题讨论】:

    标签: javascript html canvas blob


    【解决方案1】:

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

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

    我猜你的 blob 格式正确,你可以这样发送。

    【讨论】:

    • 感谢您的回复 :)
    • 我认为我有一个格式良好的 blob,但 JSON.stringify 仍然只是返回一个 emtpy 对象“{}”。控制台日志中的 blob 看起来像: Blob {size: 1996683, type: "image/png"} size: 1996683 type: "image/png" proto: Blob 有什么想法吗?还有一个问题,我无法将我的 typeorm 数据库中的 blob 保存为 blob .. 它总是保存为空,不知道两者是否相关
    • @white91wolf json.stringify 返回一个空对象是正常的,这就是这个答案所说的。对于你的数据库,我一无所知。
    【解决方案2】:
    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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2016-04-25
      • 2015-02-09
      • 1970-01-01
      • 2015-10-28
      • 2021-02-13
      • 2021-03-31
      • 2020-04-29
      相关资源
      最近更新 更多