Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created June 8, 2010 15:19
Show Gist options
  • Save gavinblair/430172 to your computer and use it in GitHub Desktop.
Save gavinblair/430172 to your computer and use it in GitHub Desktop.
Generate thumbnails on the fly
<?php
if (!isset($_GET['src'])) {
//for testing, navigate to thumbnail.php?img=page/to/yourimage.jpg
echo "<img src='/thumbnail.php?src={$_GET['img']}' />";
} else {
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Pragma: no-cache"); // HTTP/1.0
header("Content-type: image/pjpeg");
header("Cache-Control: private");
header("Content-Description: PHP Generated Data");
//get the size of the image
//$_GET['src'] can be a URL or a path
list($width, $height) = getimagesize($_GET['src']);
//if specifying a height, set it
$newheight = isset($_GET['h']) ? $_GET['h'] : 66;
//calculate the proportional width, if height is set
$newwidth = isset($_GET['h']) ? ($width * ($newheight / $height)) : 96;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($_GET['src']);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//this echoes out the jpg
imagejpeg($thumb);
}
@gavinblair
Copy link
Author

Is this crazy?

@SeanJA
Copy link

SeanJA commented Jun 8, 2010

Perhaps because you are generating it every time? You could save it, check if the source image has changed then create a new one. This would only be a problem if you were getting hit a whole pile. Also, you might find that you will run out of memory if you load a massive image.

header("Content-type: image/pjpeg"); => header("Content-type: image/jpeg");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment