单张图片上传,重命名和制成缩略图

include 'FileUpload.class.php'; //上传文件

$upload = new \FileUpload();

//设置附件上传目录在/Home/temp下
$path = './upfiles/' . $attr['order_sn'] . '/';
$upload->savePath = $path; // 设置附件上传目录
$upload->saveRule = '';
//存在同名文件是否是覆盖
$upload->uploadReplace = true;
//move_uploaded_file($_FILES["upfile"]["tmp_name"], $filepath . $randname); //
//单文件上传

if (!$upload->upload()) {  //如果上传失败,提示错误信息
    $this->error($upload->getErrorMsg());
} else {  //上传成功
    //获取上传文件信息
    $info = $upload->getUploadFileInfo();
    //重命名
    $new_name = $attr['order_sn'] . "-" . $attr['num'] . "-1";
    $fileName = $info[0]['savename']; //得到上传文件的名字
    $name = explode('.', $fileName); //将文件名以'.'分割得到后缀名,得到一个数组
    $newPath = $path . $new_name . '.' . $name[1]; //得到一个新的文件为'20070705163148.jpg',即新的路径
    $oldPath = $path . $fileName; //临时文件夹,即以前的路径
    rename($oldPath, $newPath); //重命名
    //小图路径
    $smg_path = $path."sm_".$new_name.".".$name[1];
    $result = mkThumbnail($newPath, 90, 90,$smg_path); //缩略图
}
function mkThumbnail($src, $width = null, $height = null, $filename = null) { //制作缩略图   $filename  保存路径 (不指定直接输出在浏览器) $src 原图片路径
    if (!isset($width) && !isset($height))
        return false;
    if (isset($width) && $width <= 0)
        return false;
    if (isset($height) && $height <= 0)
        return false;

    $size = getimagesize($src);
    if (!$size)
        return false;

    list($src_w, $src_h, $src_type) = $size;
    $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;
    $src_img = $imagecreatefunc($src);
    $dest_img = imagecreatetruecolor($width, $height);
    imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);

    $imagefunc = 'image' . $img_type;
    if ($filename) {
        $imagefunc($dest_img, $filename);
    } else {
        header('Content-Type: ' . $src_mime);
        $imagefunc($dest_img);
    }
    imagedestroy($src_img);
    imagedestroy($dest_img);
    return true;
}

猜你喜欢

转载自blog.csdn.net/admin1008611/article/details/77823218