search
HomeBackend DevelopmentPHP TutorialPHP image upload class and generate thumbnails

  1. /**
  2. * Upload pictures
  3. */
  4. class imgUpload{
  5. static protected $a;
  6. protected $formName; //Form name
  7. protected $directory; //File uploaded to directory
  8. protected $ maxSize; //Maximum file upload size
  9. protected $canUpload; //Whether it can be uploaded
  10. protected $doUpFile; //Uploaded file name
  11. protected $sm_File; //Thumbnail name
  12. private function __construct($_formName='file ', $_directory='./images/uploads/', $_maxSize=1048576){ //1024*1024=1M
  13. //Initialization parameters
  14. $this->formName = $_formName;
  15. $this->directory = $_directory;
  16. $this->maxSize = $_maxSize;
  17. $this->canUpload = true;
  18. $this->doUpFile = '';
  19. $this->sm_File = '';
  20. }
  21. //Determine whether the image is within the allowed format
  22. static public function Type($_formName='file'){
  23. $_type = $_FILES[$_formName]['type'];
  24. switch ($_type){
  25. case ' image/gif':
  26. if (self::$a==NULL)
  27. self::$a = new imgUpload($_formName);
  28. break;
  29. case 'image/pjpeg':
  30. if (self::$a ==NULL)
  31. self::$a = new imgUpload($_formName);
  32. break;
  33. case 'image/x-png':
  34. if (self::$a==NULL)
  35. self::$a = new imgUpload($_formName);
  36. break;
  37. default:
  38. self::$a = false;
  39. }
  40. return self::$a;
  41. }
  42. //Get the file size
  43. public function getSize($_format=' K'){
  44. if ($this->canUpload) {
  45. if (0 == $_FILES[$this->formName]['size']) {
  46. $this->canUpload = false;
  47. return $this->canUpload;
  48. break;
  49. }
  50. switch ($_format){
  51. case 'B':
  52. return $_FILES[$this->formName]['size'];
  53. break;
  54. case 'K ':
  55. return round($_FILES[$this->formName]['size'] / 1024);
  56. break;
  57. case 'M':
  58. return round($_FILES[$this->formName][' size'] / (1024*1024),2);
  59. break;
  60. }
  61. }
  62. }
  63. //Get the file type
  64. public function getExt(){
  65. if ($this->canUpload) {
  66. $_name = $_FILES[$this->formName]['name'];
  67. $_nameArr = explode('.',$_name);
  68. $_count = count($_nameArr)-1;
  69. }
  70. return $_nameArr[ $_count];
  71. }
  72. //Get the file name
  73. public function getName(){
  74. if ($this->canUpload) {
  75. return $_FILES[$this->formName]['name'];
  76. }
  77. }
  78. //Create a new file name
  79. public function newName(){
  80. return date('YmdHis').rand(0,9);
  81. }
  82. //Upload a file
  83. public function upload(){
  84. if ($this->canUpload)
  85. {
  86. $_getSize = $this->getSize('B');
  87. if (!$_getSize)
  88. {
  89. return $_getSize;
  90. break;
  91. }
  92. else
  93. {
  94. $_newName = $this->newName();
  95. $_ext = $this->getExt();
  96. $_doUpload = move_uploaded_file($_FILES[$this->formName]['tmp_name'], $this->directory.$_newName.".".$_ext);
  97. if ($_doUpload)
  98. {
  99. $this->doUpFile = $_newName;
  100. }
  101. return $_doUpload;
  102. }
  103. }
  104. }
  105. //创建缩略图
  106. public function thumb($_dstChar='_m', $_max_len=320){ //$_dstChar:_m , _s
  107. if ($this->canUpload && $this->doUpFile != "") {
  108. $_ext = $this->getExt();
  109. $_srcImage = $this->directory.$this->doUpFile.".".$_ext;
  110. //得到图片信息数组
  111. $_date = getimagesize($_srcImage, &$info);
  112. $src_w = $_date[0]; //源图片宽
  113. $src_h = $_date[1]; //源图片高
  114. $src_max_len = max($src_w, $src_h); //求得长边
  115. $src_min_len = min($src_w, $src_h); //求得短边
  116. $dst_w = ''; //目标图片宽
  117. $dst_h = ''; //目标图片高
  118. //宽高按比例缩放,最长边不大于$_max_len
  119. if ($src_max_len>$_max_len)
  120. {
  121. $percent = $src_min_len / $src_max_len;
  122. if ($src_w == $src_max_len)
  123. {
  124. $dst_w = $_max_len;
  125. $dst_h = $percent * $dst_w;
  126. }
  127. else
  128. {
  129. $dst_h = $_max_len;
  130. $dst_w = $percent * $dst_h;
  131. }
  132. }
  133. else
  134. {
  135. $dst_w = $src_w;
  136. $dst_h = $src_h;
  137. }
  138. //建立缩略图时,源图片的位置
  139. $src_x = '';
  140. $src_y = '';
  141. //判断如果缩略图用于logo,将对其进行裁减
  142. if ('s_' == $_dstChar) {
  143. $src_x = $src_w * 0.10;
  144. $src_y = $src_h * 0.10;
  145. $src_w *= 0.8;
  146. $src_h *= 0.8;
  147. }
  148. //判断图片类型并创建对应新图片
  149. switch ($_date[2]){
  150. case 1:
  151. $src_im = imagecreatefromgif($_srcImage);
  152. break;
  153. case 2:
  154. $src_im = imagecreatefromjpeg($_srcImage);
  155. break;
  156. case 3:
  157. $src_im = imagecreatefrompng($_srcImage);
  158. break;
  159. case 8:
  160. $src_im = imagecreatefromwbmp($_srcImage);
  161. break;
  162. }
  163. //创建一幅新图像
  164. if ($_date[2]==1) { //gif无法应用imagecreatetruecolor
  165. $dst_im = imagecreate($dst_w, $dst_h);
  166. }else {
  167. $dst_im = imagecreatetruecolor($dst_w, $dst_h);
  168. }
  169. //Make a thumbnail copy of this image
  170. // $bg = imagecolorallocate($dst_im,255,255,0);
  171. imagecopyresized($dst_im,$src_im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  172. //Perform anti-aliasing operation on the image
  173. imageantialias($dst_im, true);
  174. switch ($_date[2]) {
  175. case 1:
  176. $cr = imagegif($ dst_im, $this->directory.$this->doUpFile.$_dstChar.".".$_ext, 100);
  177. break;
  178. case 2:
  179. $cr = imagejpeg($dst_im, $this-> directory.$this->doUpFile.$_dstChar.".".$_ext, 100);
  180. break;
  181. There is a problem with case 3://imagepng, so use imagejpg instead here
  182. $cr = imagejpeg($dst_im, $this->directory.$this->doUpFile.$_dstChar.".".$_ext, 100);
  183. break;
  184. }
  185. // $cr = imagejpeg($dst_im, $this->directory. $_dstChar.$this->doUpFile, 90);
  186. if ($cr) {
  187. $this->sm_File = $this->directory.$this->doUpFile.$_dstChar.".".$ _ext;
  188. return $this->sm_File;
  189. }else {
  190. return false;
  191. }
  192. }
  193. imagedestroy($dst_im);
  194. imagedestroy($cr);
  195. }
  196. //Get the uploaded file name
  197. public function getUpFile(){
  198. if ($this->doUpFile!='') {
  199. $_ext = $this->getExt();
  200. return $this->doUpFile.".".$_ext ;
  201. }else {
  202. return false;
  203. }
  204. }
  205. //Get the full path of the uploaded file
  206. public function getFilePatch(){
  207. if ($this->doUpFile!='') {
  208. $_ext = $this->getExt();
  209. return $this->directory.$this->doUpFile.".".$_ext;
  210. }else {
  211. return false;
  212. }
  213. }
  214. //Get abbreviation Full path of thumbnail file
  215. public function getThumb(){
  216. if ($this->sm_File!='') {
  217. return $this->sm_File;
  218. }else {
  219. return false;
  220. }
  221. }
  222. // Get the path of the uploaded file
  223. public function getDirectory(){
  224. if ($this->directory!='') {
  225. return $this->directory;
  226. }else {
  227. return false;
  228. }
  229. }
  230. }
  231. ?>
Copy code

Image upload, PHP


Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 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.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

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.

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool