Home Backend Development PHP Tutorial PHP image upload class; supports watermark-date folder-generated thumbnails, supports multiple file uploads

PHP image upload class; supports watermark-date folder-generated thumbnails, supports multiple file uploads

Jul 25, 2016 am 08:46 AM

You can use {Y}{m}{n} to change the current date
  1. set_dir(dirname(__FILE__).'/upload/','{y}/{m}'); //Save path, Supports {y}{m}{d} options
  2. $up->set_thumb(100,80); //Thumbnail size setting. The unit is pixels
  3. $up->set_watermark(dirname(__FILE__). '/jblog/images/watermark.png',6,90); //Watermark setting
  4. $fs = $up->execute(); //Start execution
  5. var_dump($fs); //View for testing Class situation
  6. }
  7. ?>
  8. /////View form---------
  9. test
  10. //Support multiple image uploads
  11. */
  12. class upload {
  13. var $dir; //Physical directory where attachments are stored
  14. var $time; //Customized file upload time
  15. var $allow_types; //Allow upload attachment types
  16. var $field; //Upload control name
  17. var $maxsize; //Maximum allowed file size, unit is KB
  18. var $thumb_width; //Thumbnail width
  19. var $thumb_height; //Thumbnail height
  20. var $watermark_file; //Watermark image address
  21. var $watermark_pos; //Watermark Position
  22. var $watermark_trans;//Watermark transparency
  23. //Constructor
  24. //$types: File types allowed to be uploaded, $maxsize: Allowed size, $field: Upload control name, $time: Custom upload time
  25. function upload($types = 'jpg|png', $maxsize = 1024, $field = 'attach', $time = '') {
  26. $this->allow_types = explode('|',$types);
  27. $ this->maxsize = $maxsize * 1024;
  28. $this->field = $field;
  29. $this->time = $time ? $time : time();
  30. }
  31. //Set and create file Specific storage directory
  32. //$basedir: base directory, must be a physical path
  33. //$filedir: custom subdirectory, available parameters {y}, {m}, {d}
  34. function set_dir($basedir,$filedir = '') {
  35. $dir = $basedir;
  36. !is_dir($dir) && @mkdir($dir,0777);
  37. if (!empty($filedir)) {
  38. $filedir = str_replace(array('{ y}','{m}','{d}'),array(date('Y',$this->time),date('m',$this->time),date(' d',$this->time)),strtolower($filedir));//Use string_replace to replace {y} {m} {d} tags
  39. $dirs = explode('/',$filedir );
  40. foreach ($dirs as $d) {
  41. !empty($d) && $dir .= $d.'/';
  42. !is_dir($dir) && @mkdir($dir,0777);
  43. }
  44. }
  45. $this->dir = $dir;
  46. }
  47. //Picture thumbnail settings, no need to set if thumbnails are not generated
  48. //$width: thumbnail width, $height: thumbnail height
  49. function set_thumb ($width = 0, $height = 0) {
  50. $this->thumb_width = $width;
  51. $this->thumb_height = $height;
  52. }
  53. //Picture watermark settings, if not generated add watermark There is no need to set it
  54. //$file: watermark image, $pos: watermark position, $trans: watermark transparency
  55. function set_watermark ($file, $pos = 6, $trans = 80) {
  56. $this->watermark_file = $ file;
  57. $this->watermark_pos = $pos;
  58. $this->watermark_trans = $trans;
  59. }
  60. /*——————————————————————-
  61. Execute file upload, and return an array of file information containing upload success or failure after processing,
  62. Where: name is File name. When the upload is successful, it is the file name uploaded to the server. If the upload fails, it is the local file name. dir is the physical path to store the attachment on the server. This value does not exist if the upload fails. Size is the size of the attachment. If the upload fails, it does not exist. The existence of this value
  63. flag is the status identifier, 1 means success, -1 means the file type is not allowed, -2 means the file size exceeds
  64. ———————————————————————– */
  65. function execute() {
  66. $files = array(); //Successfully uploaded file information
  67. $field = $this->field;
  68. $keys = array_keys($_FILES[$field]['name' ]);
  69. foreach ($keys as $key) {
  70. if (!$_FILES[$field]['name'][$key]) continue;
  71. $fileext = $this->fileext($_FILES[ $field]['name'][$key]); //Get the file extension
  72. $filename = date('Ymdhis',$this->time).mt_rand(10,99).'.'.$ fileext; //Generate file name
  73. $filedir = $this->dir; //The actual directory where attachments are stored
  74. $filesize = $_FILES[$field]['size'][$key]; //File size
  75. //File type not allowed
  76. if (!in_array($fileext,$this->allow_types)) {
  77. $files[$key]['name'] = $_FILES[$field]['name'][$ key];
  78. $files[$key]['flag'] = -1;
  79. continue;
  80. }
  81. //File size exceeded
  82. if ($filesize > $this->maxsize) {
  83. $files[ $key]['name'] = $_FILES[$field]['name'][$key];
  84. $files[$key]['name'] = $filesize;
  85. $files[$key][' flag'] = -2;
  86. continue;
  87. }
  88. $files[$key]['name'] = $filename;
  89. $files[$key]['dir'] = $filedir;
  90. $files[$ key]['size'] = $filesize;
  91. //Save uploaded files and delete temporary files
  92. if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {
  93. move_uploaded_file($_FILES [$field]['tmp_name'][$key],$filedir.$filename);
  94. @unlink($_FILES[$field]['tmp_name'][$key]);
  95. $files[$key][ 'flag'] = 1;
  96. //Add watermark to the picture and generate thumbnails. The demonstration here only supports jpg and png (if the gif is generated, the frame will be lost)
  97. if (in_array($fileext,array('jpg ','png'))) {
  98. if ($this->thumb_width) {
  99. if ($this->create_thumb($filedir.$filename,$filedir.'thumb_'.$filename)) {
  100. $ files[$key]['thumb'] = 'thumb_'.$filename; //Thumbnail file name
  101. }
  102. }
  103. $this->create_watermark($filedir.$filename);
  104. }
  105. }
  106. }
  107. return $files;
  108. }
  109. //Create thumbnails, generate thumbnails with the same extension
  110. //$src_file: source image path, $thumb_file: thumbnail path
  111. function create_thumb ($src_file,$thumb_file) {
  112. $t_width = $this->thumb_width;
  113. $t_height = $this->thumb_height;
  114. if (!file_exists($src_file)) return false;
  115. $src_info = getImageSize($src_file);
  116. / /If the source image is less than or equal to the thumbnail, copy the source image as the thumbnail, eliminating the need for operation
  117. if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {
  118. if (! copy($src_file,$thumb_file)) {
  119. return false;
  120. }
  121. return true;
  122. }
  123. //Calculate thumbnail size proportionally
  124. if (($src_info[0]-$t_width) > ($src_info [1]-$t_height)) {
  125. $t_height = ($t_width / $src_info[0]) * $src_info[1];
  126. } else {
  127. $t_width = ($t_height / $src_info[1]) * $ src_info[0];
  128. }
  129. //Get the file extension
  130. $fileext = $this->fileext($src_file);
  131. switch ($fileext) {
  132. case 'jpg' :
  133. $src_img = ImageCreateFromJPEG($src_file); break;
  134. case 'png' :
  135. $src_img = ImageCreateFromPNG($src_file); break;
  136. case 'gif' :
  137. $src_img = ImageCreateFromGIF($src_file); break;
  138. }
  139. //Create a true color thumbnail image
  140. $thumb_img = @ImageCreateTrueColor($t_width,$t_height);
  141. //The image copied by the ImageCopyResampled function has better smoothness, priority is given
  142. if (function_exists('imagecopyresampled')) {
  143. @ImageCopyResampled($thumb_img,$src_img, 0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);
  144. } else {
  145. @ImageCopyResized($thumb_img,$src_img,0,0,0,0,$ t_width,$t_height,$src_info[0],$src_info[1]);
  146. }
  147. //Generate thumbnails
  148. switch ($fileext) {
  149. case 'jpg' :
  150. ImageJPEG($thumb_img,$thumb_file); break;
  151. case 'gif' :
  152. ImageGIF($thumb_img,$thumb_file); break;
  153. case 'png' :
  154. ImagePNG($thumb_img,$thumb_file); break;
  155. }
  156. //Destroy temporary image
  157. @ImageDestroy
  158. return true //If the file does not exist, return
  159. if (!file_exists($this->watermark_file) || !file_exists($file)) return;
  160. if (!function_exists('getImageSize')) return;
  161. //Check GD Supported file types
  162. $gd_allow_types = array();
  163. if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';
  164. if (function_exists('ImageCreateFromPNG')) $gd_allow_types[' image/png'] = 'ImageCreateFromPNG';
  165. if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';
  166. //Get file information
  167. $fileinfo = getImageSize($file) ;
  168. $wminfo = getImageSize($this->watermark_file);
  169. if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;
  170. if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {
  171. if (array_key_exists($wminfo['mime'],$gd_allow_types)) {
  172. //Create image from file
  173. $temp = $gd_allow_types[ $fileinfo['mime']]($file);
  174. $temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);
  175. //Watermark position
  176. switch ($this-> ;watermark_pos) {
  177. case 1 : // Top left
  178. $dst_x = 0; $dst_y = 0; break;
  179. case 2 : // Top center
  180. $dst_x = ($fileinfo[0] - $wminfo[0]) /2; $dst_y = 0; break;
  181. case 3 : //Top right
  182. $dst_x = $fileinfo[0]; $dst_y = 0; break;
  183. case 4 : //Bottom left
  184. $dst_x = 0; $dst_y = $fileinfo[1]; break;
  185. case 5: //Centered at the bottom
  186. $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;
  187. case 6: //bottom right
  188. $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;
  189. default : //random
  190. $ dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);
  191. }
  192. if (function_exists('ImageAlphaBlending' )) ImageAlphaBlending($temp_wm,True); //Set the color blending mode of the image
  193. if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //Save the complete alpha channel information
  194. //For the image Add watermark
  195. if (function_exists('imageCopyMerge')) {
  196. ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1],$this->watermark_trans );
  197. }else {
  198. ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);
  199. }
  200. //Save the image
  201. switch ($fileinfo['mime ']) {
  202. case 'image/jpeg' :
  203. @imageJPEG($temp,$file);
  204. break;
  205. case 'image/png' :
  206. @imagePNG($temp,$file);
  207. break;
  208. case 'image/gif' :
  209. @imageGIF($temp,$file);
  210. break;
  211. }
  212. //Destroy the zero-time image
  213. @imageDestroy($temp);
  214. @imageDestroy($temp_wm);
  215. }
  216. }
  217. }
  218. //Get the file extension
  219. function fileext($filename) {
  220. return strtolower(substr(strrchr($filename,'.'),1,10));
  221. }
  222. }
  223. ?>
Copy code

Image upload, PHP
This topic was moved by Xiaobei on 2015-11-18 08:23


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles