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.

Tags:

1 Comment

  1. It was just brought to my attention that IE 8 and prior throw a small wrench into the works.

    We're using a simple <div> element as the "cropper", which because it doesn't have any content, it's technically transparent and all mouse events "fall through" to the image below.

    To prevent this, we can fill the div with a repeating transparent background:

    #photo-cropper { background: url('one-pixel-transparent-background.gif'); }

Leave a Reply

Your email address will not be published. Required fields are marked *