Jquery & PHP Doing Simple Image Slicing

Today i was in need of a basic image slicer. An there must be a million of these things out there. But i wanted to see how hard / easy it would be to create this myself.

Conclusion. It’s not that hard when using the jquery library. which is becoming my Javascript framework of choice.

<script src="js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>

I started with a div.

<div id="image_slicer_canvas"></div>

Then i added the placeholder for the to be scaled image. And a div that will represent the slicer borders.

<div id="image_slicer_canvas">
  <img src="images/sample.jpg" alt="" border="0" id="image_slicer_image"></img>
  <div id="image_slicer">
    <div id="image_slicer_scaler" class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se"></div>
  </div>
</div>

The next thing to do is setup the scaling canvas. So let’s make it draggable and resizeable.

// Create a draggable / scalable slicer
$(function() {
  $('#image_slicer')
    .draggable({containment:'#image_slicer_canvas'}) // constraint
    .resizable();
    
  // set the slicer canvas size
  resizeCanvas(
    $('#image_slicer_image').width(),
    $('#image_slicer_image').height()
  );
});

The only thing we need now is a bit of javascript to handle the slice action. I used a sample form to do the posting to the slicer.php script

// handle slicer actions
$('#image_slicer').resizable({
  stop: function(event, ui) { 
    var pos = $('#image_slicer').position();
  
    // width, height, left, top
    $('#scaler_width').val($('#image_slicer').width());
    $('#scaler_height').val($('#image_slicer').height());
    $('#scaler_left').val(pos.left);
    $('#scaler_top').val(pos.top);
  }
});

The result is a nice red dotted line (square) on top of the image. The dotted area is draggable and resizeable. When the right slice is selected just hit the slice button and PHP/GD will do the rest.

$width  = $_POST['width'];
$height = $_POST['height']; 
$left   = $_POST['left'];
$top    = $_POST['top'];
    
// read source image
$src = imagecreatefromjpeg('images/sample.jpg');
$dest = imagecreatetruecolor($width, $height);
    
imagecopy($dest, $src, 0, 0, $left, $top, $width, $height);
    
header('Content-Type: image/jpeg');
imagegif($dest);
    
imagedestroy($dest);
imagedestroy($src);

That’s all. All files can be downloaded here

comments powered by Disqus