Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - converting canvas to blob using cropper js

I have created an application using cropper.js for cropping an images. The application is working and the image is cropping, after that I am trying to send the cropped image as blob to the server side for storing,

As per the cropper.js documentation we can use canvas.toDataURL to get a Data URL, or use canvas.toBlob to get a blob and upload it to server with FormData. when I tried canvas.toDataURL() I am getting the base64 string, but actually I need to send the file as blob so I tried with canvas.toBlob() but I am getting Uncaught TypeError: canvas.toBlob is not a function in chrome and TypeError: Not enough arguments to HTMLCanvasElement.toBlob. in Firefox

Can anyone please tell me some solution for this

My code is like this

var canvas = $image.cropper("getCroppedCanvas", undefined);
var formData = new FormData();
formData.append('mainImage', $("#inputImage")[0].files[0]);
formData.append('croppedImage', canvas.toBlob());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The method toBlob is asynchronous and require two arguments, the callback function and image type (there is optional third parameter for quality):

void canvas.toBlob(callback, type, encoderOptions);

Example

if (typeof canvas.toBlob !== "undefined") {
  canvas.toBlob(function(blob) {
      // send the blob to server etc.
      ...
  }, "image/jpeg", 0.75);
}
else if (typeof canvas.msToBlob !== "undefined") {
  var blob = canvas.msToBlob()
  // send blob
}
else {
  // manually convert Data-URI to Blob (if no polyfill)
}

Not all browsers supports it (IE needs prefix, msToBlob, and it works differently than the standard) and Chrome needs a polyfill.

Update (to OP's edit, now removed) The main reason why the cropped image is larger is because the original is JPEG, the new is PNG. You can change this by using toDataURL:

var uri = canvas.toDataURL("image/jpeg", 0.7);  // last=quality

before passing it to the manual data-uri to Blob. I would recommend using the polyfill as if the browser supports toBlob() it will be many times faster and use less memory overhead than going by encoding a data-uri.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...