Skip to content

Instantly share code, notes, and snippets.

@alexcorvi
Created June 27, 2016 09:45
Show Gist options
  • Save alexcorvi/9f4cb537a204939a45de40071e4497ca to your computer and use it in GitHub Desktop.
Save alexcorvi/9f4cb537a204939a45de40071e4497ca to your computer and use it in GitHub Desktop.
/**
*
* input file => data URI
* image => cropped image
*
**/
(function($) {
/**
*
* File upload to data URI.
*
**/
$.file2URI = function (obj) {
if (obj.el.files && obj.el.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
obj.success(e.target.result);
}
reader.readAsDataURL(obj.el.files[0]);
}
else {
obj.error();
}
}
/**
*
* Now cropping..
*
**/
// croppie variable, the plugin needs this variable
$.croppie;
// crop function will be inside this object
$.crop = {}
/**
*
* Follwing function will take the image element and put it in a canvas
* element for viewing and cropping functionality
*
**/
$.crop.view = function (uploadElId,viewElId) {
/**
*
* Converting the view element to canvas on which the image
* will be viewed an the user will crop his image in.
*
**/
if(typeof $.croppie !== "object"){
$.croppie = new Croppie(document.getElementById(viewElId.substr(1)), {
viewport: { width: 200, height: 200, type: 'circle'},
boundary: { width: 300, height: 300 },
exif: true,
enableOrientation: true
});
}
/**
*
* Getting the image from the upload input element
* and binding it to the croppie view element.
* also displaying an error if occured.
*
**/
setTimeout(function () {
$.file2URI({
el:document.getElementById(uploadElId.substr(1)),
success:function (res) {
$.croppie.bind({
url: res,
orientation: 0
});
},
error:function () {
$('body').pgNotification({
style: 'flip',
message: "Your browser doesn't support cropping images.",
position: "bottom-right",
timeout: 0,
type: "danger"
}).show();
}
});
},500);
}
$.crop.save = function (callback) {
$.croppie.result({
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
callback(resp);
});
};
$.crop.rotate = function (deg) {
$.croppie.rotate(parseInt(deg));
}
/**-------------------------------------------------------------------------
*
* Usage:
*
* You should have two elements:
* + one is for viewing (empty)
* + the other is the file upload input element
*
* -------------------------------
*
* You have to listen to two events
* 1: an event on which the user will be shown the cropping view
* this can be:
* - upload file input onchange
* - clicking a crop button
*
* 2: an event on which the cropped image will be saved
* this is usually is the "save" button.
*
*
* -------------------------------
*
* When event(1) occurs: initialize the cropping plugin on both elements
* $.crop.view("#inputElementId","#viewElementId");
*
* When event(2) occurs: convert the canvas on the view to a data URI
* $.crop.save(function(uri){
* // doe something
* });
*
*
*
*
**/
})(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment