Home php教程 php手册 php如何生成缩略图的文件上传类(附代码)

php如何生成缩略图的文件上传类(附代码)

Jun 13, 2016 am 09:48 AM
php thumbnail

这篇文章主要介绍了php可生成缩略图的文件上传类,给出了完整的类文件代码及其相应的用法示例,非常具有实用价值,需要的朋友可以参考下。

类文件调用方法如下:

代码如下:

<?php 
if ($_GET[&#39;action&#39;] == &#39;save&#39;) {         
        
    $up = new upload();         
    $up->set_dir(dirname(__FILE__).&#39;/upload/&#39;,&#39;{y}/{m}&#39;);         
    $up->set_thumb(100,80);         
    $up->set_watermark(dirname(__FILE__).&#39;/jblog/images/watermark.png&#39;,6,90);         
    $fs = $up->execute();         
        
    var_dump($fs);         
}      
?> 
<html>         
    <head><title>test</title></head>         
    <body style="margin:0;padding:0">         
    <form name="upload" method="post" action="?action=save" enctype="multipart/form-data" style="margin:0">         
        <input type="file" name="attach[]" />         
        <input type="file" name="attach[]" />         
        <input type="submit" name="submit" value="上 传" />         
    </form>         
    </body>         
</html>
Copy after login

upload上传类文件如下:

代码如下:

class upload {
    var $dir;            //附件存放物理目录         
    var $time;           //自定义文件上传时间         
    var $allow_types;    //允许上传附件类型         
    var $field;          //上传控件名称         
    var $maxsize;        //最大允许文件大小,单位为KB         
        
    var $thumb_width;    //缩略图宽度         
    var $thumb_height;   //缩略图高度         
        
    var $watermark_file; //水印图片地址         
    var $watermark_pos;  //水印位置         
    var $watermark_trans;//水印透明度         
        
    //构造函数         
    //$types : 允许上传的文件类型 , $maxsize : 允许大小 ,  $field : 上传控件名称 , $time : 自定义上传时间         
    function upload($types = &#39;jpg|png&#39;, $maxsize = 1024, $field = &#39;attach&#39;, $time = &#39;&#39;) {         
        $this->allow_types = explode(&#39;|&#39;,$types);         
        $this->maxsize = $maxsize * 1024;         
        $this->field = $field;         
        $this->time = $time ? $time : time();         
    }         
        
    //设置并创建文件具体存放的目录         
    //$basedir  : 基目录,必须为物理路径         
    //$filedir  : 自定义子目录,可用参数{y}、{m}、{d}         
    function set_dir($basedir,$filedir = &#39;&#39;) {         
        $dir = $basedir;         
        !is_dir($dir) && @mkdir($dir,0777);         
        if (!emptyempty($filedir)) {         
            $filedir = str_replace(array(&#39;{y}&#39;,&#39;{m}&#39;,&#39;{d}&#39;),array(date(&#39;Y&#39;,$this->time),date(&#39;m&#39;,$this->time),date(&#39;d&#39;,$this->time)),strtolower($filedir));         
            $dirs = explode(&#39;/&#39;,$filedir);         
            foreach ($dirs as $d) {         
                !emptyempty($d) && $dir .= $d.&#39;/&#39;;         
                !is_dir($dir) && @mkdir($dir,0777);         
            }         
        }         
        $this->dir = $dir;         
    }         
        
    //图片缩略图设置,如果不生成缩略图则不用设置         
    //$width : 缩略图宽度 , $height : 缩略图高度         
    function set_thumb ($width = 0, $height = 0) {         
        $this->thumb_width  = $width;         
        $this->thumb_height = $height;         
    }         
        
    //图片水印设置,如果不生成添加水印则不用设置         
    //$file : 水印图片 , $pos : 水印位置 , $trans : 水印透明度         
    function set_watermark ($file, $pos = 6, $trans = 80) {         
        $this->watermark_file  = $file;         
        $this->watermark_pos   = $pos;         
        $this->watermark_trans = $trans;         
    }         
        
    /*----------------------------------------------------------------       
    执行文件上传,处理完返回一个包含上传成功或失败的文件信息数组,       
    其中:name 为文件名,上传成功时是上传到服务器上的文件名,上传失败则是本地的文件名       
          dir  为服务器上存放该附件的物理路径,上传失败不存在该值       
          size 为附件大小,上传失败不存在该值       
          flag 为状态标识,1表示成功,-1表示文件类型不允许,-2表示文件大小超出       
    -----------------------------------------------------------------*/        
    function execute() {         
        $files = array(); //成功上传的文件信息         
        $field = $this->field;         
        $keys = array_keys($_FILES[$field][&#39;name&#39;]);         
        foreach ($keys as $key) {         
            if (!$_FILES[$field][&#39;name&#39;][$key]) continue;         
                     
            $fileext = $this->fileext($_FILES[$field][&#39;name&#39;][$key]); //获取文件扩展名         
            $filename = date(&#39;Ymdhis&#39;,$this->time).mt_rand(10,99).&#39;.&#39;.$fileext; //生成文件名         
            $filedir = $this->dir;  //附件实际存放目录         
            $filesize = $_FILES[$field][&#39;size&#39;][$key]; //文件大小
                     
            //文件类型不允许         
            if (!in_array($fileext,$this->allow_types)) {         
                $files[$key][&#39;name&#39;] = $_FILES[$field][&#39;name&#39;][$key];         
                $files[$key][&#39;flag&#39;] = -1;         
                continue;         
            }         
        
            //文件大小超出         
            if ($filesize > $this->maxsize) {         
                $files[$key][&#39;name&#39;] = $_FILES[$field][&#39;name&#39;][$key];         
                $files[$key][&#39;name&#39;] = $filesize;         
                $files[$key][&#39;flag&#39;] = -2;         
                continue;         
            }         
        
            $files[$key][&#39;name&#39;] = $filename;         
            $files[$key][&#39;dir&#39;] = $filedir;         
            $files[$key][&#39;size&#39;] = $filesize;         
        
            //保存上传文件并删除临时文件         
            if (is_uploaded_file($_FILES[$field][&#39;tmp_name&#39;][$key])) {         
                move_uploaded_file($_FILES[$field][&#39;tmp_name&#39;][$key],$filedir.$filename);         
                @unlink($_FILES[$field][&#39;tmp_name&#39;][$key]);         
                $files[$key][&#39;flag&#39;] = 1;         
        
                //对图片进行加水印和生成缩略图         
                if (in_array($fileext,array(&#39;jpg&#39;,&#39;png&#39;))) {         
                    if ($this->thumb_width) {         
                        if ($this->create_thumb($filedir.$filename,$filedir.&#39;thumb_&#39;.$filename)) {         
                            $files[$key][&#39;thumb&#39;] = &#39;thumb_&#39;.$filename;  //缩略图文件名         
                        }         
                    }         
                    $this->create_watermark($filedir.$filename);         
                }         
            }         
        }         
        
        return $files;         
    }         
        
    //创建缩略图,以相同的扩展名生成缩略图         
    //$src_file : 来源图像路径 , $thumb_file : 缩略图路径         
    function create_thumb ($src_file,$thumb_file) {         
        $t_width  = $this->thumb_width;         
        $t_height = $this->thumb_height;         
        
        if (!file_exists($src_file)) return false;         
        
        $src_info = getImageSize($src_file);         
        
        //如果来源图像小于或等于缩略图则拷贝源图像作为缩略图         
        if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {         
            if (!copy($src_file,$thumb_file)) {         
                return false;         
            }         
            return true;         
        }         
        
        //按比例计算缩略图大小         
        if ($src_info[0] - $t_width > $src_info[1] - $t_height) {         
            $t_height = ($t_width / $src_info[0]) * $src_info[1];         
        } else {         
            $t_width = ($t_height / $src_info[1]) * $src_info[0];         
        }         
        
        //取得文件扩展名         
        $fileext = $this->fileext($src_file);         
        
        switch ($fileext) {         
            case &#39;jpg&#39; :         
                $src_img = ImageCreateFromJPEG($src_file); break;         
            case &#39;png&#39; :         
                $src_img = ImageCreateFromPNG($src_file); break;         
            case &#39;gif&#39; :         
                $src_img = ImageCreateFromGIF($src_file); break;         
        }         
        
        //创建一个真彩色的缩略图像         
        $thumb_img = @ImageCreateTrueColor($t_width,$t_height);         
        
        //ImageCopyResampled函数拷贝的图像平滑度较好,优先考虑         
        if (function_exists(&#39;imagecopyresampled&#39;)) {         
            @ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);         
        } else {         
            @ImageCopyResized($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);         
        }         
        
        //生成缩略图         
        switch ($fileext) {         
            case &#39;jpg&#39; :         
                ImageJPEG($thumb_img,$thumb_file); break;         
            case &#39;gif&#39; :         
                ImageGIF($thumb_img,$thumb_file); break;         
            case &#39;png&#39; :         
                ImagePNG($thumb_img,$thumb_file); break;         
        }         
        
        //销毁临时图像         
        @ImageDestroy($src_img);         
        @ImageDestroy($thumb_img);         
        
        return true;         
        
    }         
        
    //为图片添加水印         
    //$file : 要添加水印的文件         
    function create_watermark ($file) {         
        
        //文件不存在则返回         
        if (!file_exists($this->watermark_file) || !file_exists($file)) return;         
        if (!function_exists(&#39;getImageSize&#39;)) return;         
                 
        //检查GD支持的文件类型         
        $gd_allow_types = array();         
        if (function_exists(&#39;ImageCreateFromGIF&#39;)) $gd_allow_types[&#39;image/gif&#39;] = &#39;ImageCreateFromGIF&#39;;         
        if (function_exists(&#39;ImageCreateFromPNG&#39;)) $gd_allow_types[&#39;image/png&#39;] = &#39;ImageCreateFromPNG&#39;;         
        if (function_exists(&#39;ImageCreateFromJPEG&#39;)) $gd_allow_types[&#39;image/jpeg&#39;] = &#39;ImageCreateFromJPEG&#39;;         
        
        //获取文件信息         
        $fileinfo = getImageSize($file);         
        $wminfo   = getImageSize($this->watermark_file);         
        
        if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;         
        
        if (array_key_exists($fileinfo[&#39;mime&#39;],$gd_allow_types)) {         
            if (array_key_exists($wminfo[&#39;mime&#39;],$gd_allow_types)) {         
                         
                //从文件创建图像         
                $temp = $gd_allow_types[$fileinfo[&#39;mime&#39;]]($file);         
                $temp_wm = $gd_allow_types[$wminfo[&#39;mime&#39;]]($this->watermark_file);         
        
                //水印位置         
                switch ($this->watermark_pos) {                      
                    case 1 :  //顶部居左         
                        $dst_x = 0; $dst_y = 0; break;                       
                    case 2 :  //顶部居中         
                        $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = 0; break;                         
                    case 3 :  //顶部居右         
                        $dst_x = $fileinfo[0]; $dst_y = 0; break;                        
                    case 4 :  //底部居左         
                        $dst_x = 0; $dst_y = $fileinfo[1]; break;                        
                    case 5 :  //底部居中         
                        $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;              
                    case 6 :  //底部居右         
                        $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;         
                    default : //随机         
                        $dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);         
                }         
        
                if (function_exists(&#39;ImageAlphaBlending&#39;)) ImageAlphaBlending($temp_wm,True); //设定图像的混色模式         
                if (function_exists(&#39;ImageSaveAlpha&#39;)) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息         
        
                //为图像添加水印         
                if (function_exists(&#39;imageCopyMerge&#39;)) {         
                    ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1],$this->watermark_trans);         
                } else {         
                    ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);         
                }         
        
                //保存图片         
                switch ($fileinfo[&#39;mime&#39;]) {         
                    case &#39;image/jpeg&#39; :         
                        @imageJPEG($temp,$file);         
                        break;         
                    case &#39;image/png&#39; :         
                        @imagePNG($temp,$file);         
                        break;         
                    case &#39;image/gif&#39; :          
                        @imageGIF($temp,$file);         
                        break;         
                }         
                //销毁零时图像         
                @imageDestroy($temp);         
                @imageDestroy($temp_wm);         
            }         
        }         
    }         
        
    //获取文件扩展名         
    function fileext($filename) {         
        return strtolower(substr(strrchr($filename,&#39;.&#39;),1,10));         
    }         
}
Copy after login

【相关教程推荐】

1. php编程从入门到精通全套视频教程 

2. php从入门到精通  

3. bootstrap教程 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles