Flickr Puzzle Mashup - Sending the Pieces
(Page 4 of 6 )
Dumping pieces to the browser is probably the trickiest part of the whole process. If we make the assumption our audience is only using Firefox then we could base64 encode the images and embed them directly inline in our HTML. I like this option since we won't have to worry about temporarily storing the images on the server or performing cleanup of stale puzzle pieces.
<?php ob_start(); imagejpeg($img, null, 100); $piece = base64_encode(ob_get_contents()); ob_end_clean(); imagedestroy($img); $seqId = $y * $numX + $x; echo "<img src=\"data:image/gif;base64,$piece\" id=\"piece$seqId\" alt=\"\"/>"; ?> |
The imagejpeg function can output its image to either a file or the output buffer. Since we don't want to deal with any extra files, I've captured the output using PHP's output buffering functions. Then it's a simple matter of encoding the output with the base64 function and echoing it to the client.
Unfortunately, Internet Explorer doesn't know how to handle the inline/encoded images. For those users to enjoy our mashup too we'll want to adopt the more vanilla solution of sending the pieces to a temporary holding folder and linking to them.
<?php $seqId = $y * $numX + $x; $tmpName = md5($url . $seqId); imagejpeg($img, "tmp/$tmpName", 100); imagedestroy($img);
echo "<img src=\"fetch.php?piece=$tmpName\" id=\"piece$seqId\" alt=\"\"/>"; ?> |
We don't want to overwrite any other image pieces that may be the temp directory so each one is given a unique filename by hashing a combination of the original Flickr url and a sequence id. The img tag links to the image through another PHP script to make sure stale images are deleted from the directory. The contents of such a file could simply be:
<?php /* output appropriate content-type header */ header("Content-Type: image/jpg");
if (isset($_GET["piece"]) && ctype_alnum($_GET["piece"]) && file_exists("tmp/" . $_GET["piece"])) {
/* pass the temp image file's contents then delete it to keep the temp directory clean */ readfile("tmp/" . $_GET["piece"]); unlink("tmp/" . $_GET["piece"]); } else { /* pass a "does not exist" image */ readfile("noexist.jpg"); } ?> |
You may also have noticed I've made sure each image has an id attribute. This comes in handy when we add drag and drop functionality next.
Next: Client-Side JavaScript >>
More Miscellaneous Articles
More By bluephoenix