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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With