讲师中心 微信公众号
AI工具推荐 视频效率加速

php SWFUpload 怎么创建缩略图并且保存到指定文件夹里面

陌瑶吖_3148

陌瑶吖_3148

发布时间:2016-05-25 17:07:04

|

1462人浏览过

|

来源于php中文网

原创

1.upload.php

<?php
/*
 * swfupload图片上传  
 */
    if (isset($_POST["PHPSESSID"])) {
        session_id($_POST["PHPSESSID"]);
    }
    session_start();
    ini_set("html_errors", "0");
    if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) ||$_FILES["Filedata"]["error"] != 0) {
        echo "错误:无效的上传!";
        exit(0);
    }
 
    // Get the image and create a thumbnail
     $file_types=explode(".",$_FILES["Filedata"]["name"]);
     $file_type=$file_types[count($file_types)-1];
    if(strtolower($file_type)=='gif' )
    {
        $img = imagecreatefromgif($_FILES["Filedata"]["tmp_name"]);
    }
    else if(strtolower($file_type)=='png')
    {
        $img = imagecreatefrompng($_FILES["Filedata"]["tmp_name"]);
    }
    else if(strtolower($file_type)=='bmp')
    {
        $img = imagecreatefromwbmp($_FILES["Filedata"]["tmp_name"]);
    }
    else
    {
        $img = imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
    }
 
    if (!$img) {
        echo "错误:无法创建图像 ". $_FILES["Filedata"]["tmp_name"];
        exit(0);
    }
 
    $width = imageSX($img);
    $height = imageSY($img);
 
    if (!$width || !$height) {
        echo "错误:无效的高或高";
        exit(0);
    }
 
    // Build the thumbnail
    $target_width = 100;
    $target_height = 100;
    $target_ratio = $target_width / $target_height;
 
    $img_ratio = $width / $height;
 
    if ($target_ratio > $img_ratio) {
        $new_height = $target_height;
        $new_width = $img_ratio * $target_height;
    } else {
        $new_height = $target_width / $img_ratio;
        $new_width = $target_width;
    }
 
    if ($new_height > $target_height) {
        $new_height = $target_height;
    }
    if ($new_width > $target_width) {
        $new_height = $target_width;
    }
 
    $new_img = ImageCreateTrueColor(100, 100);
    if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, 0)) { // Fill the image black
        echo "错误:不能填充新图片";
        exit(0);
    }
 
    if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0,0, $new_width, $new_height, $width, $height)) {
        echo "错误:不能调整大小的图像";
        exit(0);
    }
 
    if (!isset($_SESSION["file_info"])) {
        $_SESSION["file_info"] = array();
    }
    ob_start();
    imagejpeg($new_img);
    $imagevariable = ob_get_contents();
    ob_end_clean();
 
    $file_id = md5($_FILES["Filedata"]["tmp_name"] + rand()*100000);
 
    $_SESSION["file_info"][$file_id] = $imagevariable;
    echo "FILEID:" . $file_id;  // Return the file id to the script
    include("upimg.class.php");
    if(!empty($_FILES["Filedata"]) and count(explode(",",$_SESSION["upload_tem"]))<5)
    {
        $folder="upload/images/tem/".date("Y-m-d");
        $up = new upimg("$folder","$folder"); //可以写成:$up = new upimg();
        $up->autoThumb = TRUE; //可省略
        $up->srcDel=TRUE;
        $up->thumbWidth = 550; //可省略
        $up->thumbHeight = 400; //可省略
        $up->maxsize=2014; //上传文件大小单位是kb
        $result= $up->upload('Filedata'); // HTML中<input />的name属性值
        $_SESSION["upload_tem"]=$_SESSION["upload_tem"].",".$up->thumbPath;
        $_SESSION["upload_tem"]=trim($_SESSION["upload_tem"],",");
 
    }
 
?>

2.生成缩略图类upimg.class.php

<?php
class upimg{
    public $uploadFolder = 'upload'; // 图片存放目录
    public $thumbFolder = 'upload/thumb'; // 缩略图存放目录
    public $thumbWidth = ''; // 缩略图宽度
    public $thumbHeight = ''; // 缩略图高度
    public $autoThumb = ''; // 是否自动生成缩略图
    public $error = ''; // 错误信息
    public $imgPath = ''; // 上传成功后的图片位置
    public $thumbPath = ''; // 上传成功后的缩略图位置
    public $maxsize='';
 
    // 说明:初始化,创建存放目录
    function __construct($uploadFolder = 'upload', $thumbFolder = 'upload/thumb'){
        $this->uploadFolder = $uploadFolder;
        $this->thumbFolder = $thumbFolder;
        $this->_mkdir();
    }
 
    // 说明:上传图片,参数是<input />的name属性值;成功返回图片的相对URL,失败返回FALSE和错误信息(在$this->error里)
    // bool/sting upload(string $html_tags_input_attrib_name);
    function upload($inputName){ // 上传操作,参数是input标签的name属性。
        if ($this->error){ // 如果有错,直接返回(例如_mkdir)
            return FALSE;
        }
        if(!$_FILES[$inputName]["name"]){
            $this->error = '没有上传图片';
            return FALSE;
        }
        //检测文件大小
        if($_FILES[$inputName]["size"] > ($this->maxsize*1024)){
            $this->error = '上传文件'.$inputName.'太大,最大支持'.ceil($this->maxsize/1024).'kb的文件';
            return FALSE;
        }
        if($_FILES[$inputName]["name"]){
            $isUpFile = $_FILES[$inputName]['tmp_name'];
            if (is_uploaded_file($isUpFile)){
                $imgInfo = $this->_getinfo($isUpFile);
                if (FALSE == $imgInfo){
                    return FALSE;
                }
                $extName = $imgInfo['type'];
                $microSenond = floor(microtime()*10000);// 取一个毫秒级数字,4位。
                $newFileName = $uploadFolder . '/' . date('YmdHis') . $microSenond . '.' . $extName ; // 所上传图片的新名字。
                $location = $this->uploadFolder . $newFileName;
                $result = move_uploaded_file($isUpFile, $location);
                if ($result)
                {
                    if (TRUE == $this->autoThumb)
                        { // 是否生成缩略图
                             $thumb = $this->thumb($location, $this->thumbWidth, $this->thumbHeight);
                            if (FALSE == $thumb)
                            {
                                return FALSE;
                            }                       
                        }
                    //是否删除原图
                    if(TRUE==$this->srcDel)
                    {
                        @unlink ($location);
                    }
                    $this->imgPath = $location;
                    return $location;
                }else{
                    $this->error = '移动临时文件时出错';
                    return FALSE;
                }
            }else{
                $uploadError = $_FILES[$inputName]['error'];
                if (1 == $uploadError){ // 文件大小超过了php.ini中的upload_max_filesize
                    $this->error = '文件太大,服务器拒绝接收大于' . ini_get('upload_max_filesize') . '的文件';
                    return FALSE;
                }elseif (3 == $uploadError){ // 上传了部分文件
                    $this->error = '上传中断,请重试';
                    return FALSE;
                }elseif (4 == $uploadError){
                    $this->error = '没有文件被上传';
                    return FALSE;
                }elseif (6 == $uploadError){
                    $this->error = '找不到临时文件夹,请联系您的服务器管理员';
                    return FALSE;
                }elseif (7 == $uploadError){
                    $this->error = '文件写入失败,请联系您的服务器管理员';
                    return FALSE;
                }else{
                    if (0 != $uploadError){
                        $this->error = '未知上传错误,请联系您的服务器管理员';
                        return FALSE;
                    }
                } // end if $uploadError
            } // end if is_uploaded_file else
        } // end if $_FILES[$inputName]["name"]
    }
 
    // 说明:获取图片信息,参数是上传后的临时文件,成功返回数组,失败返回FALSE和错误信息
    // array/bool _getinfo(string $upload_tmp_file)
    private function _getinfo($img){
        if (!file_exists($img)){
            $this->error = '找不到图片,无法获取其信息';
            return FALSE;
        }
        $tempFile = @fopen($img, "rb");
        $bin = @fread($tempFile, 2); //只读2字节
        @fclose($tempFile);
        $strInfo = @unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
        $fileType = '';
        switch ($typeCode){ // 6677:bmp 255216:jpg 7173:gif 13780:png 7790:exe 8297:rar 8075:zip tar:109121 7z:55122 gz 31139
            case '255216':
                $fileType = 'jpg';
                break;
            case '6677':
                $fileType = 'bmp';
                break;
            case '7173':
                $fileType = 'gif';
                break;
            case '13780':
                $fileType = 'png';
                break;
            default:
                $fileType = 'unknown';
        }
        if ($fileType == 'jpg' || $fileType == 'gif' || $fileType == 'png' || $fileType == 'bmp'){
            $imageInfo = getimagesize($img);
            $imgInfo['size'] = $imageInfo['bits'];
            $imgInfo["type"] = $fileType;
            $imgInfo["width"] = $imageInfo[0];
            $imgInfo["height"] = $imageInfo[1];
            return $imgInfo;
        }else{ // 非图片类文件信息
            $this->error = '图片类型错误';
            return FALSE;
        }
    } // end _getinfo
 
   // 说明:生成缩略图,等比例缩放或拉伸
    // bool/string thumb(string $uploaded_file, int $thumbWidth, int $thumbHeight, string $thumbTail);
    function thumb($img, $thumbWidth = 300, $thumbHeight = 200,$thumbTail = '_thumb')
    {
        $filename = $img; // 保留一个名字供新的缩略图名字使用
        $imgInfo = $this->_getinfo($img,$i);
        if(FALSE == $imgInfo)
        {
            return FALSE;
        }
        $imgType = $imgInfo['type'];
        switch ($imgType)
        { // 创建一个图,并给出扩展名
            case "jpg" :
                $img = imagecreatefromjpeg($img);
                $extName = 'jpg';
                break;
            case 'gif' :
                $img = imagecreatefromgif($img);
                $extName = 'gif';
                break;
            case 'bmp' :
                $img = imagecreatefromgif($img);
                $extName = 'bmp';
                break;
            case 'png' :
                $img = imagecreatefrompng($img);
                $extName = 'png';
                break;
            default : // 如果类型错误,生成一张空白图
                $img = imagecreate($thumbWidth,$thumbHeight);
                imagecolorallocate($img,0x00,0x00,0x00);
                $extName = 'jpg';
        }
        // 缩放后的图片尺寸(小则拉伸,大就缩放)
        $imgWidth = $imgInfo['width'];
        $imgHeight = $imgInfo['height'];
        if($imgHeight > $imgWidth)
        { // 竖图
            $newHeight = $thumbHeight;
            $newWidth = ceil($imgWidth / ($imgHeight / $thumbHeight ));
        }
        else if($imgHeight < $imgWidth)
        { // 横图
            $newHeight = ceil($imgHeight / ($imgWidth / $thumbWidth ));
            $newWidth = $thumbWidth;
        }
        else if($imgHeight == $imgWidth)
        { // 等比例图
            $newHeight = $thumbWidth;
            $newWidth = $thumbWidth;
        }
        $bgimg = imagecreatetruecolor($newWidth,$newHeight);
        $bg = imagecolorallocate($bgimg,0x00,0x00,0x00);
        imagefill($bgimg,0,0,$bg);
        $sampled = imagecopyresampled($bgimg,$img,0,0,0,0,$newWidth,$newHeight,$imgWidth,$imgHeight);
        if(!$sampled )
        {
            $this->error = '缩略图生成失败';
            $this->path=$this->uploadFolder . '/' . $filename;
            return FALSE;
        }
        $filename = basename($filename);
        $newFileName = substr($filename, 0, strrpos($filename, ".")) . $thumbTail . '.' . $extName ; // 新名字
        $thumbPath = $this->thumbFolder . '/' . $newFileName;
        switch ($extName){
            case 'jpg':
                $result = imagejpeg($bgimg, $thumbPath);
                break;
            case 'gif':
                $result = imagegif($bgimg, $thumbPath);
                break;
            case 'png':
                $result = imagepng($bgimg, $thumbPath);
                break;
            default: // 上边判断类型出错时会创建一张空白图,并给出扩展名为jpg
                $result = imagejpeg($bgimg, $thumbPath);
        }
        if ($result)
        {
            $this->thumbPath = $thumbPath;
            $this->path=$this->uploadFolder . '/' . $filename;
            return $thumbPath;
        }
        else
        {
            $this->error = '缩略图创建失败';
            $this->path=$this->uploadFolder . '/' . $filename;
            return FALSE;
        }
    } // end thumb
 
   // 说明:创建图片的存放目录
    private function _mkdir()
    { // 创建图片上传目录和缩略图目录
        if(!is_dir($this->uploadFolder))
        {
            $dir = explode('/', $this->uploadFolder);
            foreach($dir as $v)
            {
                if($v)
                {
                    $d .= $v . '/';
                    if(!is_dir($d))
                    {
                        $state = mkdir($d);
                        if(!$state)
                        {
                            $this->error = '在创建目录' . $d . '时出错!';
                        }
                             
                    }
                }
            }
        }
        if(!is_dir($this->thumbFolder) && TRUE == $this->autoThumb)
        {   
            $dir = explode('/', $this->thumbFolder);
            foreach($dir as $v)
            {
                if($v)
                {
                    $d .= $v . '/';
                    if(!is_dir($d))
                    {
                        $state = mkdir($d);
                        if(!$state)
                        {
                            $this->error = '在创建目录' . $d . '时出错!';
                        }
                             
                    }
                }
            }
        }
    }
}
?>
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

火山引擎

火山引擎是一款面向企业的云计算与AI服务平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

Laper
Laper Hot

Laper是专为编剧、导演和制片人推出的 AI 原生剧本创作工具。

相关专题

更多
Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

200

2026.09.23

Buffalo框架路由与请求处理实操指南
Buffalo框架路由与请求处理实操指南

本专题讲解Buffalo框架路由与请求处理机制,涵盖路由注册与分组、资源路由、Handler编写规范、Context上下文方法、参数绑定、中间件编写挂载、Session与Cookie读写、Flash消息及错误页面定制方法。

100

2026.09.23

Buffalo框架零基础入门教程
Buffalo框架零基础入门教程

本专题整理Buffalo框架入门内容,涵盖Go环境准备、buffalo CLI安装、新项目生成、目录结构说明、dev热加载启动、数据库连接配置与常见报错排查,帮助新手按约定优于配置的思路跑通第一个Buffalo框架应用。

80

2026.09.23

Conan创建软件包配方指南
Conan创建软件包配方指南

本专题介绍通过conanfile.py创建软件包的方法,讲解包名、版本、依赖和构建设置等基础信息,以及source、build、package、package_info等常用方法的作用及编写思路。

60

2026.09.22

Conan二进制包配置指南
Conan二进制包配置指南

本专题介绍Conan根据操作系统、编译器、架构和构建类型生成二进制包的方法,讲解Profile、Settings、Options及Package ID的作用,帮助管理不同平台和编译环境下的包版本。

60

2026.09.22

Conan私有仓库搭建教程
Conan私有仓库搭建教程

本专题系统的讲解Conan私有仓库的搭建流程,涵盖仓库服务部署、存储目录配置、用户认证、权限划分和远程地址添加,并介绍内部C++依赖包的上传、下载及版本维护方法。

60

2026.09.22

loomy官网入口地址合集
loomy官网入口地址合集

本专题汇总了 Loomy 桌面 AI 助理的官方入口地址合集及使用指南。提供 macOS 与 Windows 客户端下载 。Loomy 是讯飞推出的桌面级 AI 工作搭子,支持文件整理、数据分析、网页操作及通过飞书/钉钉远程操控电脑,助你高效完成本地办公任务 。

60

2026.09.22

NumPy常见函数使用方法
NumPy常见函数使用方法

本专题整理 NumPy 常见函数使用方法相关教程,覆盖函数大全、参数用法、数组运算、统计聚合、排序处理、where 条件筛选、linspace 创建数列等常用场景,帮助读者快速掌握 NumPy 函数调用思路和实际数据处理技巧。

80

2026.09.22

NumPy性能优化版本更新与常见报错排查
NumPy性能优化版本更新与常见报错排查

本专题整理 NumPy 性能优化、版本更新与常见报错排查相关教程,覆盖向量化计算、广播性能、内存布局、NumPy 2.0 升级、版本兼容冲突、安装导入报错、dtype 溢出、矩阵运算异常和 broadcasting 报错修复,帮助读者系统掌握 NumPy 性能调优与问题定位方法。

100

2026.09.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn