php gd 缩略图,[PHP GD库]①0--缩略图封装

/** 返回图片信息

* @param $filename

*/

function getImageInfo($filename)

{

if (@!$info = getimagesize($filename)) {

exit("文件不是真实图片");

}

/**

* array

* 0 => int 756

* 1 => int 960

* 2 => int 2

* 3 => string 'width="756" height="960"' (length=24)

* 'bits' => int 8

* 'channels' => int 3

* 'mime' => string 'image/jpeg' (length=10)

*/

$fileInfo['width'] = $info[0];//756

$fileInfo['height'] = $info[1];//960

$mime = image_type_to_mime_type($info[2]);//image/jpeg

$createFun = str_replace('/', 'createfrom', $mime);

$outFun = str_replace('/', '', $mime);

$fileInfo['createFun'] = $createFun;

$fileInfo['outFun'] = $outFun;

$fileInfo['ext'] = strtolower(image_type_to_extension($info[2]));

return $fileInfo;

}

/**

* 形成缩略图

* @param $filename 文件名

* @param string $dest 缩略图保存路径,默认'thumb'

* @param string $pre 默认前缀thumb_

* @param null $dst_w 最大宽度

* @param null $dst_h 最大高度

* @param float $scale 默认缩放比例

* @param boolean $delSource 是否删除源文件标志

* @return string 最终保存路径及文件名

*

*/

function thumb($filename, $dest = 'thumb', $pre = 'thumb_',

$dst_w = null, $dst_h = null, $scale = 0.5, $delSource = false)

{

$fileInfo = getImageInfo($filename);

$src_w = $fileInfo['width'];

$src_h = $fileInfo['height'];

//如果指定最大宽度和高度,按照等比例缩放进行处理

if (is_numeric($dst_w) && is_numeric($dst_h)) {

$ratio_orig = $src_w / $src_h;

if ($dst_w / $dst_h > $ratio_orig) {

$dst_w = $dst_h * $ratio_orig;

} else {

$dst_h = $dst_w / $ratio_orig;

}

} else {

$dst_w = ceil($src_w * $scale);

$dst_h = ceil($src_h * $scale);

}

$dst_image = imagecreatetruecolor($dst_w, $dst_h);

$src_image = $fileInfo['createFun']($filename);

imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);

if ($dest && !file_exists($dest)) {

mkdir($dest, 07777, true);

}

$randNum = mt_rand(100000, 999999);

$dstName = "{$pre}{$randNum}" . $fileInfo['ext'];

$destination = $dest ? $dest . '/' . $dstName : $dstName;

$fileInfo['outFun']($dst_image, $destination);

imagedestroy($src_image);

imagedestroy($dst_image);

if ($delSource) {

@unlink($filename);

}

return $destination;

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值