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.
I started with a div.
Then i added the placeholder for the to be scaled image. And a div that will represent the slicer borders.
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



Thijs Lensselink is a PHP developer, consultant and all out open source enthusiast.
He has over 12+ years of experience in building and maintaining web applications mostly
on linux/Unix/BSD platforms. Besides a full time job he does freelance work with his ...