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.

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


Tagged , .

Updated: 2011-08-05

Phil LaNasa follow us in feedly
  • admin

    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'); }