<?php
/**
* 指定缩放比例
* 最大宽度和高度,等比例缩放
* 可以对缩略图文件添加前缀
* 选择是否删除缩略图的源文件
*/
/**
* 返回图片的文件信息
*
* @param [string] $filename
* @return void
*/
function getInfo($filename)
{
if ($info = getimagesize($filename)) {
$fileInfo['width'] = $info[0];
$fileInfo['height'] = $info[1];
$mime = $info['mime'];
$createFun = str_replace('/', 'createfrom', $mime);
$outFun = str_replace('/', '', $mime);
$fileInfo['createFun'] = $createFun;
$fileInfo['outFun'] = $outFun;
$fileInfo['ext'] = image_type_to_extension($info[2]);
return $fileInfo;
}
}
/**
* 形成缩略图的函数
*
* @param [string] $filename 文件名
* @param [string] $dest 缩略图保存路径,默认保存在thumb目录下
* @param [string] $pre 默认前缀为thumb_
* @param [number] $dst_w 最大宽度
* @param [number] $dst_h 最大高度
* @param [float] $scale 默认缩放比例
* @param [boolean] $delRourse 是否删除源文件标志
* @return void 最终保存路径及文件名
*/
function thumb($filename, $dest = 'thumb', $pre = 'thumb_', $dst_w = null, $dst_h = null, $scale = 0.5, $delRourse = false)
{
// $filename = '../images/1.jpg';
// $scale = 0.5;
// $dst_w = 300;
// $dst_h = 200;
// $dest = 'thumb';
// $pre = 'thumb_';
// $delRourse = false;
$fileInfo = getInfo($filename);
$src_w = $fileInfo['width'];
$src_h = $fileInfo['height'];
if (is_numeric($dst_w) && is_numeric($dst_h)) {
$prop = $src_w / $src_h;
if ($dst_w / $dst_h > $prop) {
$dst_w = $dst_h * $prop;
} else {
$dst_h = $dst_w / $prop;
}
} else {
$dst_w = $src_w * $scale;
$dst_h = $src_h * $scale;
}
$src_image = $fileInfo['createFun']($filename);
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
if ($dest && !file_exists($dest)) {
mkdir($dest, 0777, true);
}
$randNum = mt_rand(100000, 999999);
$dstName = "{$pre}{$randNum}" . $fileInfo['ext'];
$destination = $dest . '/' . $dstName;
$fileInfo['outFun']($dst_image, $destination);
imagedestroy($dst_image);
imagedestroy($src_image);
return $destination;
}
网友评论