Flickr Puzzle Mashup - Slicing the Image
(Page 3 of 6 )
Once we've got an image for our puzzle, we can cut it up into pieces. The number of total pieces is based on how many times we'll slice the image lengthwise and by height. For example, if we cut the image 4 times horizontally and 3 times vertically we'll get a total of 12. While 12 sounds like a good default number, we can also have x and y parameters the user can specify to override this.
<?php $numX = (isset($_GET["x"]) && ctype_digit($_GET["x"]) && $_GET["x"] > 0) ? $_GET["x"] : 4; $numY = (isset($_GET["y"]) && ctype_digit($_GET["y"]) && $_GET["y"] > 0) ? $_GET["y"] : 3; $numPieces = $numX * $numY; ?> |
So how big does each piece need to be? We find this out by doing some simple division of the original image size by our $numX and $numY values.
<?php $pieceWidth = floor(imagesx($image) / $numX); $pieceHeight = floor(imagesy($image) / $numY); ?> |
It's possible for users to get over zealous and end up with zero-sized pieces. They should get the default values if this happens, so we'll need to reset the values of $numX, $numY and $numPieces and recalculate $pieceWidth and $pieceHeght. This is a simple check so I'll leave this step up to you.
With all our initial calculations done, all that's left to do is loop through and slice the images up into pieces. Slicing is done here by creating a new image in memory with the imagecreatetruecolor function and copying the desired section from the original image to it with imagecopy.
<?php for ($y = 0; $y < $numY; $y++) { for ($x = 0; $x < $numX; $x++) { $img = imagecreatetruecolor($pieceWidth, $pieceHeight); imagecopy($img, $image, 0, 0, $pieceWidth * $x, $pieceHeight * $y, $pieceWidth, $pieceHeight); // ... dump the piece to the browser } } ?> |
Next: Sending the Pieces >>
More Miscellaneous Articles
More By bluephoenix