|
function thumb($src, $width, $height, $filename, $mode = 'scale', $quality = '100') {
try {
$imageValue = getimagesize($src);
$sourceWidth = $imageValue[0]; //原图宽
$sourceHeight = $imageValue[1]; //原图高
$thumbWidth = $width; //缩略图宽
$thumbHeight = $height; //缩略图高
$_x = 0;
$_y = 0;
$w = $sourceWidth;
$h = $sourceHeight;
if ($mode == 'scale') {
if ($sourceWidth $s2) { //全高度
$y = 0;
$ax = floor($sourceWidth * ($thumbHeight / $sourceHeight));
$x = ($ax - $thumbWidth) / 2;
$w = $thumbWidth / ($thumbHeight / $sourceHeight);
} else { //全宽度
$x = 0;
$ay = floor($sourceHeight * ($thumbWidth / $sourceWidth)); //模拟原图比例高度
$y = ($ay - $thumbHeight) / 2;
$h = $thumbHeight / ($thumbWidth / $sourceWidth);
}
}
switch ($imageValue[2]) {
case 2: $source = imagecreatefromjpeg($src);
break;
case 1: $source = imagecreatefromgif($src);
break;
case 3: $source = imagecreatefrompng($src);
break;
case 6: $source = imagecreatefromwbmp($src);
break;
default: defulat();
return;
}
header("Content-type: image/jpeg");
$thumb = imagecreatetruecolor($width, $height);
imagefill($thumb, 0, 0, imagecolorallocate($thumb, 255, 255, 255));
imagecopyresampled($thumb, $source, 0, 0, $x, $y, $width, $height, $w, $h);
imagejpeg($thumb, null, $quality);
imagejpeg($thumb, $filename, $quality);
imagedestroy($thumb);
imagedestroy($source);
} catch (Exception $ex) {
defulat();
}
}
function defulat() {
/*
$default_img = realpath('../pictures/nopic.gif');
ob_start();
header('Content-type:image/jpeg');
readfile($default_img);
ob_flush();
flush();
*/
echo 'error';
}
function mkDirs($dir){
if(!is_dir($dir)){
if(!mkDirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0755)){
return false;
}
}
return true;
}
$uri=$_SERVER['REQUEST_URI'];
$image=basename($uri);
$temp='./temp/'.dirname($uri).'/';
$imgpath='.'.dirname($uri).'/';
/*
//检查本地是否存在文件,原图
if(file_exists($temp.$image)){
ob_start();
header('Content-type:image/jpeg');
readfile($temp.$image);
ob_flush();
flush();
exit();
}
*/
//检查生成的图片是否曾经生成过,存在即返回,否则重新生成新图
if(!preg_match('/_(\d+)x(\d+)/', $image, $wh)){
ob_start();
header('Content-type:image/jpeg');
readfile($imgpath.$image);
ob_flush();
flush();
exit();
}
$width = $wh[1];
$height = $wh[2];
$source_img=preg_replace('/_(\d+)x(\d+)/', '', $image);
//对长宽都超过的图片返回原图
if($width>=2000 || $height>=2000){
ob_start();
header('Content-type:image/jpeg');
readfile($imgpath.$source_img);
ob_flush();
flush();
exit();
}
//图片处理
$src=$imgpath.$source_img;
$filename=$temp.$image;
mkDirs($temp);
//thumb(realpath($src), $width, $height, $filename, 'crop', '85');
thumb(realpath($src), $width, $height, $filename, 'crop', '100');
|
|
|