5

i am using cropperjs to crop images

Using the method getCroppedCanvas to get reference to the cropped canvas image

Using the canvas method canvas.toDataURL to compress the images into a jpeg files.

I don't use canvas.toBlob as its browser support is not clear.

My question is how can i turn the string i get from canvas.toDataURL into a blob so i can later use it in formData.

Update

server expect form data - multi-part

Neta Meta
  • 4,001
  • 9
  • 42
  • 67

2 Answers2

6

One method that I used while working on some tool is to convert the dataURL to Blob using this function:

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

And then you can send the Blob to the server using native xhr like this:

var blob = dataURLtoBlob(dataURI);
var fd = new FormData();
var xhr = new XMLHttpRequest ();

fd.append ('file', blob);
xhr.open('POST', '/endpoint', true);

xhr.onerror = function () {
    console.log('error');
}

xhr.onload = function () {
    console.log('success')
}

xhr.send (fd);

The blob builder code is taken from here: https://stackoverflow.com/a/30407840/2386736

abhishekkannojia
  • 2,796
  • 23
  • 32
0

use canvas.toDataURL to generate an JPEG image:

var JPEG_QUALITY=0.5;
var dataUrl = canvas.toDataURL('image/jpeg', JPEG_QUALITY).replace('data:image/jpeg;base64,', '');

And then send it to AJAX as data-multi-part:

jQuery.ajax({
    url: 'php/upload.php',
    data: dataUrl,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){            
    }
});

Depending on what your server side expects to receive.

By the way: You wrote "I don't use canvas.toBlob as its browser support is not clear" - You can see the browser support here:

enter image description here

Koby Douek
  • 16,156
  • 19
  • 74
  • 103