I'm using the imgly image cropper plugin, slightly modified for my app. It currently converts an image to a dataUrl
and spits out the image as a base64 image that I can save as a jpeg. I'm working on adapting the dataURItoBlob
function found here, to my app, so I can get the image posted to an API endpoint. I have the following so far, but I'm not sure how to append the final image to the xhr.open('POST', '/', true);
renderButton.click(function (event) {
var dataUrl =
imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// 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(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
}
var blob = dataURItoBlob(dataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
//Appends generated dataUrl to a div
var image = $("<img><br>").attr({
src: dataUrl
});
//Remove button
image.appendTo($(".result"))
$button = $('<button class="btn btn-default remove">')
.text('Remove Image')
.on('click', function () {
image.remove();
$(this).remove();
return false;
});
$button.appendTo($(".result"));
});
});
});