Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas to blob returns empty blob object

I'm trying to convert a canvas element image to blob. I have tried the below code using canvas-to-blob.min.js and it returns an empty object. But when converting to data URL it is not empty.

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)

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. Please help me to resolve this issue

like image 365
Dileep TP Avatar asked Jan 29 '26 15:01

Dileep TP


1 Answers

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 : "{}".

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.

like image 195
Kaiido Avatar answered Jan 31 '26 05:01

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!