Home Backend Development PHP Tutorial Create image thumbnails with PHP

Create image thumbnails with PHP

Jul 25, 2016 am 08:48 AM

  1. /**
  2. * Upload images to generate thumbnails
  3. *
  4. * Requires GD2 library support
  5. *
  6. * Parameters new thumbnails('original address of the image to be thumbnailed', 'width of thumbnail', 'height of thumbnail' are required during initialization ','(optional parameter) Thumbnail saving path');
  7. * If the last parameter is not specified, the thumbnail will be saved in the small folder in the directory of the original image by default,
  8. * If small does not exist folder, the small folder will be automatically created
  9. *
  10. * After initialization, you need to call the method produce to create thumbnails
  11. * $thumbnails = new thumbnails(''....);
  12. * $thumbnails->produce();
  13. *
  14. * You can get the relevant information of the original image, width, height, and image mime
  15. *
  16. * $thumbnails->getImageWidth(); //int image width
  17. * $thumbnails->getImageHeight(); / / int Image height
  18. * $thumbnails->getImageMime(); // string mime of the image
  19. *
  20. * $thumbnails->trueSize(); //array This is an array containing the width and sum of the image after scaling it down. Array of height values ​​
  21. * $size = array('width'=>'','height'=>'');
  22. * Get the width and height of the image after scaling it
  23. * $size['width ']//The width of the proportional thumbnail
  24. * $size['height']//The height of the proportional thumbnail
  25. *
  26. */
  27. class thumbnails{
  28. private $imgSrc; //Picture path
  29. private $saveSrc; //Picture saving path, default is empty
  30. private $ canvasWidth; //The width of the canvas
  31. private $canvasHeight; //The height of the canvas
  32. private $im; //Canvas resources
  33. private $dm; //Resources returned by copying the image
  34. /**
  35. * Initialize the class and load related settings
  36. *
  37. * @param $imgSrc The path of the image that needs to be thumbnailed
  38. * @param $canvasWidth The width of the thumbnail
  39. * @param $canvasHeight The height of the thumbnail
  40. */
  41. public function __construct($imgSrc,$canvasWidth,$canvasHeight,$saveSrc=null)
  42. {
  43. $this->imgSrc = $imgSrc;
  44. $this->canvasWidth = $canvasWidth;
  45. $this->canvasHeight = $ canvasHeight;
  46. $this->saveSrc = $saveSrc;
  47. }
  48. /**
  49. * Generate thumbnails
  50. */
  51. public function produce()
  52. {
  53. $this->createCanvas();
  54. $this->judgeImage ();
  55. $this->copyImage();
  56. $this->headerImage();
  57. }
  58. /**
  59. * Get the information of the loaded image
  60. *
  61. * Contains the length, width, and image type
  62. *
  63. * @return array An array containing the image length, width, and mime
  64. */
  65. private function getImageInfo()
  66. {
  67. return getimagesize($this- >imgSrc);
  68. }
  69. /**
  70. * Get the length of the image
  71. *
  72. * @return int The width of the image
  73. */
  74. public function getImageWidth()
  75. {
  76. $imageInfo = $this->getImageInfo();
  77. return $imageInfo['0'];
  78. }
  79. /**
  80. * Get the height of the image
  81. *
  82. * @return int The height of the image
  83. */
  84. public function getImageHeight()
  85. {
  86. $imageInfo = $this->getImageInfo();
  87. return $imageInfo['1'];
  88. }
  89. /**
  90. * Get the type of image
  91. *
  92. * @return the mime value of the image
  93. */
  94. public function getImageMime()
  95. {
  96. $imageInfo = $this->getImageInfo();
  97. return $imageInfo['mime'];
  98. }
  99. /**
  100. * Create canvas
  101. *
  102. * At the same time, put the created canvas resource into the attribute $this->im
  103. */
  104. private function createCanvas ()
  105. {
  106. $size = $this->trueSize();
  107. $this->im = imagecreatetruecolor($size['width'],$size['height']);
  108. }
  109. /* *
  110. * Determine the mime value of the image and determine the function to use
  111. *
  112. * At the same time, put the created image resource into $this->dm
  113. */
  114. private function judgeImage()
  115. {
  116. $mime = $this->getImageMime();
  117. switch ($mime)
  118. {
  119. case 'image/png':$dm = imagecreatefrompng($this ->imgSrc);
  120. break;
  121. case 'image/gif':$dm = imagecreatefromgif($this->imgSrc);
  122. break;
  123. case 'image/jpg':$dm = imagecreatefromjpeg($this ->imgSrc);
  124. break;
  125. case 'image/jpeg':$dm = imagecreatefromgjpeg($this->imgSrc);
  126. break;
  127. }
  128. $this->dm = $dm;
  129. }
  130. /**
  131. * Determine the width and height of the image after being reduced
  132. *
  133. * This width and height are also used as the size of the canvas
  134. *
  135. * @return array The size of the image after being reduced in equal proportions
  136. */
  137. public function trueSize()
  138. {
  139. $proportionW = $this->getImageWidth() / $this->canvasWidth;
  140. $proportionH = $this->getImageHeight() / $this->canvasHeight;
  141. if( ($this->getImageWidth() < $this->canvasWidth) && ($this->getImageHeight() < $this->canvasHeight) )
  142. {
  143. $trueSize = array('width'=>$this->getImageWidth(),'height'=>$this->getImageHeight());
  144. }
  145. elseif($proportionW >= $proportionH)
  146. {
  147. $trueSize = array('width'=>$this->canvasWidth,'height'=>$this->getImageHeight() / $proportionW);
  148. }
  149. else
  150. {
  151. $trueSize = array('width'=>$this->getImageWidth() / $proportionH,'height'=>$this->canvasHeight);
  152. }
  153. return $trueSize;
  154. }
  155. /**
  156. * Copy the image to a new canvas
  157. *
  158. * The image will be scaled proportionally and will not be deformed
  159. */
  160. private function copyImage()
  161. {
  162. $size = $this->trueSize();
  163. imagecopyresized($this->im, $this->dm , 0 , 0 , 0 , 0 , $size['width'] , $size['height'] , $this->getImageWidth() , $this->getImageheight());
  164. }
  165. /**
  166. * Export the image
  167. *
  168. * The name of the image is the same as the original image name by default
  169. *
  170. * The path is the small directory under the current directory of the large image
  171. *
  172. * If the small directory does not exist, it will be automatically created
  173. */
  174. public function headerImage()
  175. {
  176. $position = strrpos($this->imgSrc,'/');
  177. $imageName = substr($this->imgSrc,($position + 1));
  178. if($this->saveSrc)
  179. {
  180. $imageFlode = $this->saveSrc.'/';
  181. }
  182. else
  183. {
  184. $imageFlode = substr($this->imgSrc,0,$position).'/small/';
  185. }
  186. if(!file_exists($imageFlode))
  187. {
  188. mkdir($imageFlode);
  189. }
  190. $saveSrc = $imageFlode.$imageName;
  191. imagejpeg($this->im,$saveSrc);
  192. }
  193. }
复制代码


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

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 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...

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 late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

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�...

See all articles