SiteKickr Web Development

A basic draggable photo cropper

If you have user generated photos, and wish to crop them down to a thumbnail, it's not always easy to decide which area of the photo to crop. It generally makes sense to let the user make that decision.

With jQuery and AJAX at our side, this task can be made relatively simple. See the example below.

The HTML

<div id="photo-wrapper">
    <img src="myphoto.jpg" width="xxx" height="xxx" alt="" />
</div>

The CSS

#photo-wrapper { position: relative;
                                border: 1px solid #000; }
#photo-cropper { position: absolute;
                               left: 0;
                               top: 0;
                               width: xxxpx;   // the width of the cropping region
                               height: xxxpx;  // the height of the cropping region
                               border: 1px dashed #eee;
                               cursor: move; }

 

The jQuery

$('#photo-wrapper').append('<div id="photo-cropper"></div>');
$('#photo-cropper').draggable({
    containment : 'parent',
    stop: function(event, ui) {
        $('#photo-cropper').draggable('disable');
        $.ajax({
            url : 'yourProcessingScript.php&x=' + ui.position.left + '&y=' + ui.position.top,
            complete : function() {
                $('#photo-cropper').draggable('enable');
            }
        });
    }
});

 

You may need to pass additional arguments to your processing script in the AJAX url. Your processing script would most likely store the cropping x and y positions in your database, then perform image manipulation on the original image.