Skip to content

Instantly share code, notes, and snippets.

@jasny
Created May 30, 2012 14:53
Show Gist options
  • Save jasny/2836824 to your computer and use it in GitHub Desktop.
Save jasny/2836824 to your computer and use it in GitHub Desktop.
Thumbnail creator in PHP
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ ../thumb.php [QSA,L]
</IfModule>
<img src="400x300.myimage.jpg" />
<img src="200x200-crop.myimage.jpg" />
<?php
function createthumb($name, $filename, $new_w, $new_h, $crop=false)
{
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if ($ext =='jpg') $ext = 'jpeg';
$fn_create = "imagecreatefrom$ext";
$fn_out = "image$ext";
if (!function_exists($fn_create)) throw new Exception("Unsupported extension '$ext' for '$name'");
$src_img = $fn_create($name);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$old_x = 0;
$old_y = 0;
if ($old_w < $new_w && $old_h < $new_h) {
copy($name, $filename);
return;
}
if (($old_w / $new_w) > ($old_h / $new_h) xor $crop) {
$thumb_w=$new_w;
$thumb_h=$old_h*($new_w/$old_w);
if ($crop) $old_y = floor(0.5 * ($thumb_h - $new_h) * ($new_w/$old_w));
} else {
$thumb_w=$old_w*($new_h/$old_h);
$thumb_h=$new_h;
if ($crop) $old_x = floor(0.5 * ($thumb_w - $new_w) * ($new_h/$old_h));
}
$dst_img = imagecreatetruecolor($crop ? $new_w : $thumb_w, $crop ? $new_h : $thumb_h);
imagesavealpha($dst_img, true);
$trans_colour = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
imagefill($dst_img, 0, 0, $trans_colour);
imagecopyresampled($dst_img, $src_img, 0, 0, $old_x, $old_y, $thumb_w, $thumb_h, $old_w, $old_h);
$fn_out($dst_img, $filename);
imagedestroy($dst_img);
imagedestroy($src_img);
}
$newfile = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/' . ltrim(isset($_GET['name']) ? $_GET['name'] : preg_replace('/\?.*$/', '', $_SERVER['REQUEST_URI']), '/');
$dir = dirname($newfile);
if (!preg_match('/^(\d+)x(\d+)(?:-(crop))?\.(.*\.(.*?))$/', basename($newfile), $match)) {
header('HTTP/1.0 404 Not Found');
echo "Illegal filename '$newfile'";
exit;
}
list(, $width, $height, $crop, $name, $ext) = $match;
createthumb("$dir/$name", $newfile, $width, $height, (bool)$crop);
if (!file_exists($newfile)) {
header('HTTP/1.0 500 Internal Server Error');
echo "Could not write to '$newfile'";
exit;
}
$ext = strtolower($ext);
if ($ext =='jpg') $ext = 'jpeg';
header("Content-Type: image/$ext");
readfile($newfile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment