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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles