/**
* 生成缩略图函数(支持图片格式:gif、jpeg、png和bmp)
* @author ruxing.li
* @param string $src 源图片路径
* @param int $width 缩略图宽度(只指定高度时进行等比缩放)
* @param int $width 缩略图高度(只指定宽度时进行等比缩放)
* @param string $filename 保存路径(不指定时直接输出到浏览器)
* @return bool
* @param array $size 图像的信息
* @param string $src_mime 图像的MIME
* @param string $src_type 图像的类型
* @param string $src_h 图像的原始高
* @param string @src_w 图像的原始宽
* @param string @imagefunc 输出图象到浏览器或文件的对应函数。
*/
function mkThumbnail($src, $width = null, $height = null, $filename = null) {
//如果宽和高都不存在
if (!isset($width) && !isset($height))
return false;
//如果宽存在,但是宽小于0
if (isset($width) && $width <= 0)
return false;
//如果高存在,但是高小于0
if (isset($height) && $height <= 0)
return false;
$size = getimagesize($src);
/*获取图像尺寸
array(7) {
[0] => int(130) //[0]原始宽
[1] => int(130) //[1]原始高
[2] => int(2) //[2]图像的类型(1 = GIF,
6 = BMP,7 = TIFF(intel byte order),
8 = TIFF(motorola byte order),
9 = JPC,10 = JP2,11 = JPX,
12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM)
//[3]给出的是一个宽度和高度的字符串,可以直接用于 HTML 的 <image> 标签
[3] => string(24) "width="130" height="130""
["bits"] => int(8) //bits 给出的是图像的每种颜色的位数,二进制格式
["channels"] => int(3) //channels 给出的是图像的通道值,RGB 图像默认是 3
//mime 给出的是图像的 MIME 信息,此信息可以用来在 HTTP Content-type 头信息中发送正确的信息,
如:header("Content-type: image/jpeg");
["mime"] => string(10) "image/jpeg"
}
*/
if (!$size)
return false;
//将原始宽、原始高、图像类型放入
list($src_w, $src_h, $src_type) = $size;
//图像的类型 "image/jpeg"
$src_mime = $size['mime'];
switch($src_type) {
case 1 :
$img_type = 'gif';
break;
case 2 :
$img_type = 'jpeg';
break;
case 3 :
$img_type = 'png';
break;
case 15 :
$img_type = 'wbmp';
break;
default :
return false;
}
//如果没有设置宽
if (!isset($width))
$width = $src_w * ($height / $src_h);
//如果没有设置高
if (!isset($height))
$height = $src_h * ($width / $src_w);
//获取对应的图像函数
$imagecreatefunc = 'imagecreatefrom' . $img_type;
//由文件或 URL 创建一个新图象
$src_img = $imagecreatefunc($src);
//返回一个图像标识符,代表了一幅大小为 x_size 和 y_size 的黑色图像
$dest_img = imagecreatetruecolor($width, $height);
/*
参数1: 新建的图片
参数2: 需要载入的图片/老图片
参数3: 设定需要载入的图片在新图中的x坐标
参数4: 设定需要载入的图片在新图中的y坐标
参数5: 设定载入图片要载入的区域x坐标
参数6: 设定载入图片要载入的区域y坐标
参数7: 设定载入的原图的宽度(在此设置缩放)
参数8: 设定载入的原图的高度(在此设置缩放)
参数9: 原图要载入的宽度
参数10:原图要载入的高度
*/
imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
$imagefunc = 'image' . $img_type;
if ($filename) {
// imagefunc 输出图象到浏览器或文件。
$imagefunc($dest_img, $filename);
} else {
header('Content-Type: ' . $src_mime);
//输出图像到浏览器
$imagefunc($dest_img);
}
//销毁新、旧图像
imagedestroy($src_img);
imagedestroy($dest_img);
return true;
}
PHP原生--缩略图的生成
最新推荐文章于 2021-03-19 15:54:46 发布