If you don't have image manipulation capabilities available on your server, fortunately, you can still implement a basic photo cropping tool using pure CSS & JavaScript.

Key CSS Ingredients:

  • Negative margins
  • Overflow property

Key JavaScript Ingredients:

  • jQuery
  • jQuery UI

 

On the cropping tool side, you can leverage jQuery mobile's draggable and resizeable tools to create a very basic UI for cropping a photo.

 

Cropping Tool

The HTML

<div id="wrapper">
    <img src="myimage.jpg" alt="" id="image" />
    <span id="thumb"></span> <!-- the cropping boundaries -->
</div>

The CSS

#wrapper { position: relative; width: maxImageWidthpx; height: maxImageHeightpx; }
#image { position: absolute; top: 0; left: 0; max-width: maxImageWidthpx; max-height: maxImageHeightpx; }
#thumb { position: absolute; top: 0; left: 0; width: cropWidthpx; height: cropHeightpx; border: 2px dashed #aaa; cursor: move;  }   

The jQuery

var width = $('img').width();
var height = $('img').height();
$('img').resizable({
    aspectRatio : true,
    containment: 'parent',
    minWidth: cropWidth,
    minHeight: cropHeight,
    handles: 'se',
    stop : function(event, ui) {
        var width = $('img').width();
        var height = $('img').height();
        $('#thumb').draggable('option', 'containment', [0, 0, width - cropWidth, height - cropHeight]);
        $.ajax({
            url: 'updateTable.php?id=' + id + '&width=' + width + '&height=' + height
        })
    }   
});
$('#thumb').draggable({
    containment : [0, 0, width - cropWidth, height - cropHeight],
    stop : function(event, ui) {
        $.ajax({
            url: 'updateTable.php?id=' + id + '&x=' + ui.position.left + '&y=' + ui.position.top
        })
    }   
});

Note the php scripts used within the jQuery AJAX calls.  These simply contain the code which will update your database table with the new width, height, x, y positions of the cropping region and image size.
 

One the front end, we make use of the CSS properties mentioned above (negative margins and overflow) to effectively crop the full photo within a wrapper.

Front End

The HTML

<span id="photo-wrapper">
  <img src="myimage.jpg"
           width="<?php echo $widthFromDB; ?>"
           height="<?php echo $heightFromDB;?>"
           style="margin: -<?php echo $yFromDB; ?>px 0 0 -<?php echo $xFromDB; ?>px;"
           alt="" />
</span>

The CSS

#photo-wrapper { display: block; width: cropWidthpx; height: cropHeightpx; overflow: hidden; }

Tags:

Leave a Reply

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