PHP image upload class instance to generate thumbnails

Source: Internet
Author: User
Tags add watermark to picture imagejpeg
This article mainly introduces PHP can generate thumbnails of the file upload class, give the complete class file code and its corresponding usage example, very practical value, the need for friends can refer to the following

This article describes the file upload class and its usage for PHP to generate thumbnails. Share to everyone for your reference. The implementation method is as follows:

Class file Invocation method is as follows:

 
  Set_dir (DirName (__file__). ' /upload/', ' {y}/{m} ');             $up->set_thumb (100,80);             $up->set_watermark (DirName (__file__). ' /jblog/images/watermark.png ', 6,90);             $fs = $up->execute ();             Var_dump ($FS);         }      ? >              Test                                                

Upload upload class file as follows:

Class Upload {var $dir;           The attachment holds the physical directory var $time;    Custom file upload time var $allow _types;          Allow upload of attachment type var $field;        Upload control name Var $maxsize;    Maximum allowable file size in KB var $thumb _width;   Thumbnail width var $thumb _height; Thumbnail height var $watermark _file;  Watermark Image address Var $watermark _pos; Watermark location var $watermark _trans;//watermark Transparency//constructor//$types: Allowed file types to upload, $maxsize: allowable size, $  Field: Upload control name, $time: Custom upload Time function upload ($types = ' jpg|png ', $maxsize = 1024x768, $field = ' Attach ', $time                 = ') {$this->allow_types = explode (' | ', $types);                 $this->maxsize = $maxsize * 1024;                 $this->field = $field; $this->time = $time?             $time: Time ();             }//Set up and create file specific directory//$basedir: Base directory, must be 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; }//Picture thumbnail settings, if you do not generate thumbnails do not set//$width: Thumbnail width, $height: thumbnail height function set_thumb ($widt                 H = 0, $height = 0) {$this->thumb_width = $width;             $this->thumb_height = $height; }//Picture watermark settings, if not generated add watermark does not set//$file: Watermark picture, $pos: WaterPrint position, $trans: Watermark transparency Function Set_watermark ($file, $pos = 6, $trans =) {$this->waterma                 Rk_file = $file;                 $this->watermark_pos = $pos;             $this->watermark_trans = $trans;            }/*----------------------------------------------------------------perform a file upload and return an array of file information containing the success or failure of the upload.  Where: Name is the filename, upload success is uploaded to the server file name, upload failure is the local file name dir is the physical path to the server to hold the attachment, upload failure does not exist this value size For attachment size, upload failure does not exist this value flag is the status identifier, 1 indicates success, 1 indicates that the file type is not allowed, and 2 indicates that the file size exceeds---------------------------------------                 --------------------------*/function Execute () {$files = array ();//File information uploaded successfully                 $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]); Gets the file name extension $filename = date (' Ymdhis ', $this->time). Mt_rand (10,99). $fileext;  Generate file name $filedir = $this->dir; The attachment is actually stored in the catalogue $filesize = $_files[$field] [' size '] [$key]; File size//file type does not allow if (!in_array ($fileext, $this->allow_types)) {$                         files[$key [' name '] = $_files[$field [' name '] [$key];                         $files [$key] [' flag '] =-1;                     Continue }//File size exceeds 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; Save the upload file and delete the temporary file if (Is_uploaded_file ($_files[$field] [' tmp_name '] [$key])) {MOV                         E_uploaded_file ($_files[$field] [' tmp_name '] [$key], $filedir. $filename);                         @unlink ($_files[$field [' tmp_name '] [$key]);                         $files [$key] [' flag '] = 1; Watermark and generate thumbnails if (In_array ($fileext, array (' jpg ', ' png ')) {if ($thi S->thumb_width) {if ($this->create_thumb ($filedir. $filename, $filedir. ' Thumb_ '. $file  Name) {$files [$key] [' thumb '] = ' thumb_ '. $filename; Thumbnail file name}} $this->create_wate                         Rmark ($filedir. $filename);             }}} return $files; }//create thumbnails with the same extensioninto thumbnails//$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;                     }//proportionally calculate thumbnail size 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]; }//Get file extension $fileext = $this->filEext ($src _file); Switch ($fileext) {case ' jpg ': $src _img = imagecreatefromjpeg ($src _file); BR                     Eak 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 smoothness of the imagecopyresampled function copy is good, preferably if (function_exists (' imagecopyresampled ')) {@Im                 Agecopyresampled ($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]);                         }//Generate thumbnail 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 image @ImageDestroy ($src _img);                 @ImageDestroy ($thumb _img);             return true; }//Add watermark to Picture//$file: File to add Watermark function Create_watermark ($file) {//text                 If the piece does not exist then return if (!file_exists ($this->watermark_file) | | |!file_exists ($file)) return;                 if (!function_exists (' getimagesize ')) return;                 Check the file types supported by 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 ';                 Get file Information $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 _al                          Low_types) {//Create image from File $temp = $gd _allow_types[$fileinfo [' MIME ']] ($file);                         $temp _wm = $gd _allow_types[$wminfo [' MIME ']] ($this->watermark_file); Watermark Position switch ($this->watermark_pos) {Case 1://Top Left $dst _x = 0; $DST _y = 0;                                           Break Case 2://top center $DST _x = ($fiLEINFO[0]-$wminfo [0])/2; $DST _y = 0;                                             Break Case 3://top right $DST _x = $fileinfo [0]; $DST _y = 0;                                            Break Case 4://Bottom left $dst _x = 0; $DST _y = $fileinfo [1];                                            Break Case 5://Bottom Center $dst _x = ($fileinfo [0]-$wminfo [0])/2; $DST _y = $fileinfo [1];                                  Break Case 6://Bottom right $dst _x = $fileinfo [0]-$wminfo [0]; $DST _y = $fileinfo [1]-$wminfo [1];                             Break Default://random $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); Sets the image's color-mixing mode if (function_exists (' ImagesavealpHa ')) imagesavealpha ($temp _wm,true);                             Save the full alpha channel information//add watermark to the image 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], $w                         MINFO[1]); }//Save picture switch ($fileinfo [' MIME ']) {case ' im                                 Age/jpeg ': @imageJPEG ($temp, $file);                             Break                                 Case ' image/png ': @imagePNG ($temp, $file);                             Break                                 Case ' image/gif ': @imageGIF ($temp, $file);                         Break                      }   Destroy Zero Image @imageDestroy ($temp);                     @imageDestroy ($temp _wm); }}}//Get file name extension function Fileext ($filename) {return s             Trtolower (substr (STRRCHR ($filename, '. '), 1,10)); }         }

I hope this article is helpful to everyone's PHP programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.