Home > Backend Development > PHP Tutorial > PHP file upload class example that can generate thumbnails, _PHP tutorial

PHP file upload class example that can generate thumbnails, _PHP tutorial

WBOY
Release: 2016-07-13 10:11:32
Original
938 people have browsed it

php file upload class instance that can generate thumbnails,

The example in this article describes the file upload class and its usage that can generate thumbnails in PHP. Share it with everyone for your reference. The specific implementation method is as follows:

The class file calling method is as follows:

Copy code The code is as follows:
if ($_GET['action'] == 'save') {                                                                                      
$up = new upload(); $up = new upload();
$up->set_dir(dirname(__FILE__).'/upload/','{y}/{m}'); $up->set_thumb(100,80); $up->set_thumb(100,80);
$up->set_watermark(dirname(__FILE__).'/jblog/images/watermark.png',6,90); $fs = $up->execute(); $fs = $up->execute();
                             
var_dump($fs); var_dump($fs);

?>
 
test
                                                      
                                                                                                                                                                                                                                                                                                                                                                                          




upload Upload the following files:




Copy code

The code is as follows:
class upload {
var $dir; //physical directory where attachments are stored
var $time; //Customized file upload time
var $allow_types; //Allow attachment types to be uploaded
var $field; //Upload control name
var $maxsize; //Maximum allowed file size, unit is KB
                             
var $thumb_width; //thumbnail width
var $thumb_height; //Thumbnail height
                             
var $watermark_file; //Watermark image address  
var $watermark_pos; //watermark position
var $watermark_trans;//watermark transparency
//Open source code phpfensi.com
                             
//Constructor function
//$types: file types allowed to be uploaded, $maxsize: allowed size, $field: upload control name, $time: custom upload time
Function upload($types = 'jpg|png', $maxsize = 1024, $field = 'attach', $time = '') {               $this->allow_types = explode('|',$types);                                                                                                                                                                                                                 $this->field = $field;                                                                                                                                                                                                                                                                   
//Set and create the directory where files are specifically stored. //$basedir : base directory, must be a physical path //$filedir : Custom subdirectory, available parameters {y}, {m}, {d}                               Function set_dir($basedir,$filedir = '') {          $dir = $basedir;                                                                    !is_dir($dir) && @mkdir($dir,0777);                                                              if (!emptyempty($filedir)) {                                          $filedir = str_replace(array('{y}','{m}','{d}'),array(date('Y',$this->time),date('m',$this ->time),date('d',$this->time)),strtolower($filedir));                 $dirs = explode('/',$filedir);                                                             foreach ($dirs as $d) {                                                  !emptyempty($d) && $dir .= $d.'/';                                                                                       ! is_dir($dir) && @mkdir($dir,0777);                                                                                                                                                                                                                                                     $this->dir = $dir;                                                                                                                                                              
//Image thumbnail settings, if thumbnails are not generated, no settings are required. //$width: thumbnail width, $height: thumbnail height
Function set_thumb ($width = 0, $height = 0) { Function set_thumb ($width = 0, $height = 0) {
                                                                                                                                                                                                                                                                                                                               
//Picture watermark settings, if no watermark is generated and added, there is no need to set it   
//$file: watermark image, $pos: watermark position, $trans: watermark transparency
Function set_watermark ($file, $pos = 6, $trans = 80) {
                                                                                                                                                                                                                                                                $this->watermark_trans = $trans;                                                                                                                                                              
/*------------------------------------------------ ----------------                  
Execute file upload, and return an array of file information containing upload success or failure after processing, "
Where: name is the file name. When the upload is successful, it is the file name uploaded to the server. When the upload fails, it is the local file name.
dir is the physical path where the attachment is stored on the server. This value does not exist if the upload fails.
size is the size of the attachment, this value does not exist if the upload fails
The flag is the status indicator, 1 means success, -1 means the file type is not allowed, -2 means the file size exceeds
-------------------------------------------------- ---------------*/ 
function execute() {
           $files = array(); //Successfully uploaded file information                                                                                                      $field = $this->field;                                           $keys = array_keys($_FILES[$field]['name']);                                                                         foreach ($keys as $key) {                                         if (!$_FILES[$field]['name'][$key]) continue;                                                                                                                 $fileext = $this->fileext($_FILES[$field]['name'][$key]); //Get the file extension                                                                                                                $filename = date('Ymdhis',$this->time).mt_rand(10,99).'.'.$fileext; // Generate file name                                                                                                          $filedir = $this->dir; //The actual directory where the attachment is stored                                                                                                                        $filesize = $_FILES[$field]['size'][$key]; //File size
                                                                                                                                                                                                                                                                              //File type not allowed            if (!in_array($fileext,$this->allow_types)) {        
                $files[$key]['name'] = $_FILES[$field]['name'][$key];        
                $files[$key]['flag'] = -1;        
                continue;        
            }        
       
            //文件大小超出        
            if ($filesize > $this->maxsize) {        
                $files[$key]['name'] = $_FILES[$field]['name'][$key];        
                $files[$key]['name'] = $filesize;        
                $files[$key]['flag'] = -2;        
                continue;        
            }        
       
            $files[$key]['name'] = $filename;        
            $files[$key]['dir'] = $filedir;        
            $files[$key]['size'] = $filesize;        
       
            //保存上传文件并删除临时文件        
            if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {        
                move_uploaded_file($_FILES[$field]['tmp_name'][$key],$filedir.$filename);        
                @unlink($_FILES[$field]['tmp_name'][$key]);        
                $files[$key]['flag'] = 1;        
       
                //对图片进行加水印和生成缩略图        
                if (in_array($fileext,array('jpg','png'))) {        
                    if ($this->thumb_width) {        
                        if ($this->create_thumb($filedir.$filename,$filedir.'thumb_'.$filename)) {        
                            $files[$key]['thumb'] = 'thumb_'.$filename;  //缩略图文件名        
                        }        
                                                                                                                                                                                                                                                                                                                                                                              through $this->create_watermark($filedir.$filename);                                                                                                                                                                                                                                                                                         
          return $files;                                                                                                                                                         
//Create thumbnails, generate thumbnails with the same extension
//$src_file: source image path, $thumb_file: thumbnail path 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 the source image is less than or equal to the thumbnail, copy the source image as the thumbnail
              if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {                                         if (!copy($src_file,$thumb_file)) {                                                                     return false;                                                                                                                                                 return true;                                                                                                                                                           
//Calculate thumbnail size proportionally If ($src_info[0] - $t_width > $src_info[1] - $t_height) {
               $t_height = ($t_width / $src_info[0]) * $src_info[1];                                                                                                                                                                      $t_width = ($t_height / $src_info[1]) * $src_info[0];                                                                                                                                                                                   
                                                                                                                                                                               // get the file extension                                             $fileext = $this->fileext($src_file);                                                                                           
switch ($fileext) {
           case 'jpg':                                                        $src_img = ImageCreateFromJPEG($src_file); break;                                                                      case 'png':                                                           $src_img = ImageCreateFromPNG($src_file); break;                                                                case 'gif':                                                        $src_img = ImageCreateFromGIF($src_file); break;                                                                                                                                                                                            
//Create a true-color thumbnail image          $thumb_img = @ImageCreateTrueColor($t_width,$t_height);                                                                                           
                                     //The image copied by the ImageCopyResampled function has better smoothness, priority is given                                                                                                    If (function_exists('imagecopyresampled')) {                                                           @ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);                                                                                                                                                 @ImageCopyResized($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);                                                                                                                                                                    
//Generate thumbnails
switch ($fileext) {
           case 'jpg':                                     ImageJPEG($thumb_img,$thumb_file); break;
           case 'gif':                                     ImageGIF($thumb_img,$thumb_file); break;
           case 'png':                                      ImagePNG($thumb_img,$thumb_file); break;
                                                                                                                          
               // Destroy temporary images                                          @ImageDestroy($src_img);                                                                @ImageDestroy($thumb_img);                                                                                      
        return true;                                                                       
                                                                                               
//Add a watermark to the image
//$file: the file to be watermarked
function create_watermark ($file) {
                             
//If the file does not exist, return If (!file_exists($this->watermark_file) || !file_exists($file)) return;        if (!function_exists('getImageSize')) return;        
                
        //检查GD支持的文件类型        
        $gd_allow_types = array();        
        if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';        
        if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';        
        if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';        
       
        //获取文件信息        
        $fileinfo = getImageSize($file);        
        $wminfo   = getImageSize($this->watermark_file);        
       
        if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;        
       
        if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {        
            if (array_key_exists($wminfo['mime'],$gd_allow_types)) {        
                        
                //从文件创建图像        
                $temp = $gd_allow_types[$fileinfo['mime']]($file);        
                $temp_wm = $gd_allow_types[$wminfo['mime']]($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('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,True); //设定图像的混色模式        
                if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息        
       
                //为图像添加水印        
                if (function_exists('imageCopyMerge')) {        
                    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['mime']) {        
                    case 'image/jpeg' :        
                        @imageJPEG($temp,$file);        
                        break;        
                      case 'image/png':                                                                                                                                                                                                             through                                                         break;                       case 'image/gif':                                                                                                                     @imageGIF($temp,$file);                                                         break;                                                                             //Destroy zero-time images                        @imageDestroy($temp);                                                                               @imageDestroy($temp_wm);                                                                                                                                                                                                                                                                                                                                              
//Get the file extension 
function fileext($filename) {
           return strtolower(substr(strrchr($filename,'.'),1,10));                                                                                                                            }


I hope this article will be helpful to everyone’s PHP programming design.




http://www.bkjia.com/PHPjc/929090.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/929090.html
TechArticle

An example of a file upload class that can generate thumbnails in php. This article describes an example of a file upload class that can generate thumbnails in php and its usage. Share it with everyone for your reference. The specific implementation method is as follows:...

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template