PHP图片剪裁代码
因为心血来潮,还是因为给SAE绑定了域名?顺便就找了一个PHP图片剪裁的代码,打算重写下图床的程序,想一想还是暂时放弃了!
PHP图片剪裁,看了网上有很多,也有很长的代码,东拼西凑的整理了一段比较短的。代码因为是配合自己SAE上图床的,大众的就没有再去整理了。
<?php
$hw=$_GET['hw'];
$wh=explode('x',$hw);
$d=$_GET['d'];
$f=$_GET['f'];
// The file
$stor = new SaeStorage();
if($stor->fileExists($d,$f)){
$filename =$stor->getUrl($d,$f);
}else{
$filename='noimg.png';
}
function file_header($a){
switch($a){
case 'png':
return 'Content-type: image/png';
break;
case 'gif':
return 'Content-type: image/gif';
break;
case 'jpg':
return 'Content-type: image/jpeg';
break;
case 'bmp':
return 'Content-type: image/bmp';
break;
default:
return 'Content-Type: application/octet-stream';
}
}
$info = pathinfo($filename);
//如果后缀获取失败则默认为jpg
if(emptyempty($info['extension'])){$info['extension'] = 'jpg';}
function imagecreatefrom($type){
global $filename;
switch($type){
case 'png':
return imagecreatefrompng($filename);
break;
case 'gif':
return imagecreatefromgif($filename);
break;
case 'jpg':
return imagecreatefromjpeg($filename);
break;
case 'bmp':
return imagecreatefromjbmp($filename);
break;
}
}
//输出文件头
$header = file_header($info['extension']);
// Set a maximum height and width
$width=null;
$height=null;
$width =!emptyempty($wh[0]) ? $wh[0]:300;
$height = !emptyempty($wh[1]) ? $wh[1]:300 ;
// Content type
//header('Content-Type: image/jpeg');
header ("{$header}");
// Get new dimensions
$list=getimagesize($filename);
//list($, ) = getimagesize($filename);
$width_orig=$list[0];
$height_orig=$list[1];
$min=$list['mime'];
if($width_orig>$height_orig){
$new_height=$height;
$new_width=$new_height/$height_orig*$width_orig;
$leftbig=($new_width-$width)/2;
$left=$leftbig/$new_width*$width;
}else{
$new_width=$width;
$new_height=$new_width/$width_orig*$height_orig;
$left=0;
}
if($new_width<$width)
{
$new_width=$width;
$new_height=$new_width/$width_orig*$height_orig;
$left=0;
}
//$ratio_orig = $width_orig/$height_orig;
//if ($width/$height > $ratio_orig) {
//$width = $height*$ratio_orig;
//} else {
//$height = $width/$ratio_orig;
//}
// Resample
$image_p = imagecreatetruecolor($width,$height);
$image = imagecreatefrom($info['extension']);
imagecopyresampled($image_p, $image, 0,0, $left,0, $new_width, $new_height, $width_orig, $height_orig);
//imagecopyresampled()
// Output
imagejpeg($image_p, null, 100);
//echo $new_width.'---'.$new_height.'---'.$min;
?>
没有图片就显示默认值,这个是配合自己程序的!
中间有一个判断header头,一个是判断 imagecreatefrom的,运行上的速度就不去纠结了。