Created
August 14, 2011 10:50
-
-
Save tzangms/1144792 to your computer and use it in GitHub Desktop.
generate thumbnail on fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Author: tzangms | |
Email: tzangms@gmail.com | |
Apache Rewrite rules | |
========================================================================================= | |
RewriteEngine On | |
RewriteBase / | |
RewriteCond %{REQUEST_URI} !=/imagick.php | |
RewriteRule ^([^.]+).(\d+)x(\d+).([^.]+)$ imagick.php?path=$1.$4&width=$2&height=$3 [L] | |
RewriteCond %{REQUEST_URI} !=/imagick.php | |
RewriteRule ^(.*)$ imagick.php?path=$1 [L] | |
========================================================================================= | |
*/ | |
$domain = 'http://tzangms.com/'; | |
# Arguments | |
$path = array_key_exists('path', $_GET) ? $_GET['path'] : null; | |
$width = array_key_exists('width', $_GET) ? $_GET['width'] : null; | |
$height = array_key_exists('height', $_GET) ? $_GET['height'] : null; | |
$if_modified_since = array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)?$_SERVER['HTTP_IF_MODIFIED_SINCE']:false; | |
if ($if_modified_since) { | |
header('HTTP/1.1 304 Not Modified'); | |
exit; | |
} | |
# Required Arguments | |
if (!$path) { | |
print "Please provide path"; | |
exit; | |
} | |
$url = $domain . $path; | |
# Fetch | |
$curl = curl_init($url); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
$return = curl_exec($curl); | |
$content_type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE); | |
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); | |
curl_close($curl); | |
# 404 Not Found | |
if ($status_code != 200) { | |
header("HTTP/1.0 404 Not Found"); | |
exit; | |
} | |
# Original | |
if (!$width and !$height) { | |
header("Content-Type: " . $content_type); | |
print $return; | |
} | |
# Thumbnail | |
$im = new Imagick(); | |
$im->readImageBlob($return); | |
# flatten GIF image | |
if ($im->getImageFormat() == 'GIF') { | |
$im->flattenImages(); | |
} | |
if ($width and !$height) { | |
$geo = $im->getImageGeometry(); | |
$ratio = $geo['width'] / $width; | |
$height = $geo['height'] / $ratio; | |
} elseif ($height and !$width) { | |
$geo = $im->getImageGeometry(); | |
$ratio = $geo['height'] / $height; | |
$width = $geo['width'] / $ratio; | |
} | |
# Output | |
$im->stripImage(); | |
$im->setImageCompressionQuality(88); | |
$im->cropThumbnailImage($width, $height); | |
header("Content-Type: " . $content_type); | |
header("Content-Length: " . strlen($im)); | |
header("Cache-Control: max-age=31536000"); | |
header("Expires: Sat, 26 Jul 2022 05:00:00 GMT"); | |
header("Last-Modified: Sat, 26 Jul 2001 05:00:00 GMT"); | |
print $im; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment