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

image_type_to_mime_type

image_type_to_extension

image.func.php

 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;
}

?>

test.php


Paste_Image.png

你可能感兴趣的:([PHP GD库]①0--缩略图封装)