需要安装php扩展imagick.
php脚本例子:
if ( empty($_GET['ReqURI']) ) {
exit('Invalid Param for ReqURI');
}
$uri = $_GET['ReqURI'];
// whether to allow creating new directory
$locked_dir_creation = false;
$source_path = dirname(str_replace('/thumbs', '',$uri));
$base_dir = "/data/www/qingluobo";
$path_tokens = explode('/', $uri);
$filename = array_pop($path_tokens);
if ( !preg_match('/(.*)_(\d+)x(\d+)_([1-3])\.(jpe?g|png|gif)/i', $filename, $matches) ){
header("Status: 404 Not Found");
echo 'invalid filename :' . $filename;
exit;
}
$source_file = $base_dir . $source_path . '/' . $matches[1];
if ( !is_file($source_file) ) {
header("Status: 404 Not Found");
echo $filename . ' Not Found';
exit;
}
$dest_path = $base_dir . implode('/', $path_tokens);
if ( !is_dir($dest_path) && $locked_dir_creation ) {
header('Status: 403 Forbidden');
echo 'Directory creation is forbidden.';
exit;
}
$new_width = $target_width = $matches[2];
$new_height = $target_height = $matches[3];
$mode = $matches[4];
$target_format = strtolower($matches[5]);
$source_img = new Imagick($source_file);
$dimension = $source_img->getImageGeometry();
$orig_width = $dimension['width'];
$orig_height = $dimension['height'];
switch ($mode) {
case '1':
break;
case '2':
/*preserve aspect ratio, resize the image to specified box,
resized image will be of specified dimension or smaller */
$new_height = $orig_height * $new_width / $orig_width;
if ($new_height > $target_height) {
$new_width = $orig_width * $target_height / $orig_height;
$new_height = $target_height;
}
break;
case '3':
/*zoom and crop the image to fill the specified dimension*/
// crop to get desired aspect ration
$desired_aspect = $target_width / $target_height;
$orig_aspect = $orig_width / $orig_height;
if ($desired_aspect > $orig_aspect) {
$trim = $orig_height - ($orig_width / $desired_aspect);
$source_img->cropImage($orig_width, $orig_height-$tirm, 0, $trim /2);
} else {
$trim = $orig_width - ($orig_height * $desired_aspect);
$source_img->cropImage($orig_width-$trim, $orig_height, $trim/2, 0);
}
break;
}
/* default mode 1, stretch image to fit the specified dimensions without preserving aspect ratio */
$source_img->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 1);
if ( !is_dir($dest_path) && !mkdir($dest_path, 0755, true) ) {
echo 'cannot create dir : ' . $dest_path;
exit;
}
$dest_file = $dest_path . '/' . $matches[0];
//file_put_contents($dest_file, $source_img);
clearstatcache($dest_path);
$source_img->writeImage($dest_file);
header("Content-Type: image/$target_format");
echo $source_img;