Skip to content

Instantly share code, notes, and snippets.

@tc
Created June 25, 2015 21:34
Show Gist options
  • Save tc/453ebd6fa0409003a7fb to your computer and use it in GitHub Desktop.
Save tc/453ebd6fa0409003a7fb to your computer and use it in GitHub Desktop.
Example of using https://github.com/fengyuanchen/cropper to crop an image and upload it to a server.
<html>
<head>
<title>Cropper example</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/0.9.1/cropper.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/0.9.1/cropper.min.js"></script>
</head>
<body>
<div class="container">
<img src="/images/picture.png">
</div>
<button onClick="postImageData()">POST Image</button>
<script>
$('.container > img').cropper({
aspectRatio: 1,
crop: function(data) {
}
});
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function postImageData() {
//e.preventDefault();
var canvas = $('.container > img').cropper('getCroppedCanvas', { width: 300, height: 300 });
var dataURL = canvas.toDataURL('image/jpeg', 0.9);
var blob = dataURItoBlob(dataURL);
var fd = new FormData();
fd.append("file", blob);
fd.append("key", "××××××××××××");
var xhr = new XMLHttpRequest();
xhr.open("POST", "/upload");
xhr.send(fd);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment