您好,欢迎光临! 推荐您使用Chrome浏览器访问本站。

PHP 缩略图 thumb.php


//限制只支持jpg,png,gif 三种格式,其余类型文件提示类型错误 (替代显示 400pic150.png 错误图片) //输出最大尺寸不超过150x150的缩略图
$img = $_GET['file']; //需要输出缩略图的地址

//调整php分配内存大小,避免出现处理图像的内存不足
//if(intval(ini_get('memory_limit')) <= 20){
//ini_set('memory_limit','20M');
//}

if(file_exists($img)&&is_file($img)){//生成缩略图
 list($imgw, $imgh, $imgt, $attr) = getimagesize($img);
 if($imgw>0&&$imgh>0){
 //计算缩小的比例,目标最长边缩至150
 $percent = $imgw>$imgh?(150/$imgw):(150/$imgh); //以最长边作为缩放参考
 if($percent<1){ //计算缩略图的新尺寸
 $new_width = floor($imgw*$percent);
 $new_height = floor($imgh*$percent);
 }else{ //如果原图尺寸小于 150x150 直接输出原图尺寸
 $new_width = $imgw;
 $new_height = $imgh;
 }
 $thumb = imagecreatetruecolor($new_width, $new_height); //创建缩略图对象
 }

 switch($imgt){ //判断格式,图像类型,但缩略图输出的都是jpg..参考下文
 case 1:
 $orgimg=imagecreatefromgif($img);
 break;
 case 2:
 $orgimg=imagecreatefromjpeg($img);
 break;
 case 3:
 $orgimg=imagecreatefrompng($img);
 break;
 default: //output 400 err 如果不是以上三种制定允许的格式,报错
 header('Content-type: image/png');
 $rec = file_get_contents("../images/400pic150.png"); //400 not a images
 echo $rec;
 die();
 break;
 }
 header('Content-type: image/jpeg'); //指定header ,告诉浏览器输出的文件为jpg
 imagecopyresampled($thumb, $orgimg, 0, 0, 0, 0, $new_width, $new_height, $imgw, $imgh); //缩放
 imagejpeg($thumb,null,85); //output image

}else{ //没有找到这个文件,报错
 header('Content-type: image/png');
 $rec = file_get_contents("../images/404pic150.png"); //404 file
 echo $rec;
}

 

参考:

http://snmoney.blog.163.com/blog/static/44005820124752232188/

http://www.knowsky.com/539572.html

您可能也喜欢