Image Processing with PHP

by , Sep. 04, 2010 at 09:09 PM

Scripts: PHP, MySQL

Have you ever asked yourself how you can process images for your website or your images API like Flickr and so on?
I have been using third part software , namely Photoshop, Gimp, Inkscape,... to resize or other image processing capabilities from those software.
Since i ve found the way to manipulate directly my images in PHP with no need of Photoshop.
I am not saying that Photoshop, Gimp,... aren't good. No they are pretty good to work with.
But PHP with gd enabled is also good, you can perfom much with this feature.

I have written a class which helps me to process my images. When I upload any image of any format or size, I don't need to manually check
weither the size or the format are good or not.
My class does all the job me. It takes the source file of the image, determine its size, its format before it resizes it and crop it to the
needed size provided to it.

With this class I can also apply watermark to my pictures and copy to it for instance an copyright image.
It works for me as fine.

In combination with Ajax, i use that class to retrieve an image from my webserver to be displayed on this site. When a next button
or prev button is clicked, ajax tries to connect to the server to get a next or prev. image that you see on my site.
For some websites with a slide show with several tens of true colored picture get a problem of the bandwidth for your site.
Using the technics of ajax, you can solve that problem, because pictures are big in bytes than text.

 

  1. <?php
  2. /**
  3. * Description of Image_Processor*
  4. * @author Emmanuel_Leonie
  5. */
  6. define("DS", DIRECTORY_SEPARATOR);
  7.  
  8. class Image_Processor
  9. {
  10. public $filename = null;
  11. public $watermark_filename = null;
  12. public $watermark = null;
  13. private $path;
  14. private $source = null;
  15. private $target = null;
  16. private $imageW;
  17. private $imageH;
  18. private $mime;
  19. //
  20. private $crop_width;
  21. private $crop_height;
  22.  
  23. public function __construct($filename, $crop_width =null, $crop_height =null, $dir =null)
  24. {
  25. $this->filename = $filename;
  26. $this->path = $dir ? $dir : "../FotosUploaded/"; //exit;
  27. if(!is_dir($this->path)) {
  28. @mkdir($dir, 0777, true);
  29. @chmod($dir, 0777);
  30. $this->path = $dir;
  31. }
  32. $this->watermark_filename = $this->path . "/watermark.png";
  33. $this->crop_width = $crop_width;
  34. $this->crop_height = $crop_height;
  35. if($this->filename)
  36. $img_str = @file_get_contents($this->filename);
  37. if($this->watermark_filename)
  38. $watermark_str = @file_get_contents($this->watermark_filename);
  39. //
  40. if(!$img_str)
  41. throw new Exception("Sorry, cannot get contents of this file.");
  42. //
  43. if(!($this->source = @imagecreatefromstring($img_str)))
  44. throw new Exception("Sorry, cannot create resource file.");
  45. //Not necessary
  46. $this->watermark = @imagecreatefromstring($watermark_str);
  47.  
  48. //Get Image size from the resource of the file;
  49. if($this->source){
  50. $this->imageW = imagesx($this->source);
  51. $this->imageH = imagesy($this->source);
  52.  
  53. }
  54. //Get image Mime type
  55. $size = getimagesize($this->filename);
  56. $this->mime = $size['mime'];
  57. }
  58.  
  59. public function getImageWidth(){
  60. return $this->imageW;
  61. }
  62.  
  63. public function getImageHeight(){
  64. return $this->imageH;
  65. }
  66.  
  67. public function getImageType(){
  68. $type = "";
  69. switch($this->mime){
  70. case "image/jpeg":
  71. case "image/jpg":
  72. case "image/pjpeg":
  73. $type = ".jpg";
  74. break;
  75. case "image/png";
  76. $type = ".png";
  77. break;
  78. case "image/gif":
  79. $type = ".gif";
  80. break;
  81. default : $type = null;
  82. break;
  83. }
  84. return $type;
  85. }
  86.  
  87. public function Resize($Width = 600, $Height = 600)
  88. {
  89. if(!$Width && !$Height)
  90. throw new Exception("You Must provide the cropped width or cropped height");
  91.  
  92. if(isset($this->imageW, $this->imageH))
  93. {
  94. if($this->imageW <= $Width && $this->imageH <= $Height)
  95. {
  96. $NewWidth = $this->imageW;
  97. $NewHeight = $this->imageH;
  98. }
  99. else
  100. {
  101. $OrigRatio =$this->imageW / $this->imageH;
  102. if(($Width/$Height) > $OrigRatio)
  103. {
  104. $NewWidth = $Height * $OrigRatio;
  105. $NewHeight = $Height;
  106. } else
  107. {
  108. $NewHeight = $Width / $OrigRatio;
  109. $NewWidth = $Width;
  110. }
  111. }
  112. $ResampledImage = imagecreatetruecolor($NewWidth, $NewHeight);
  113. imagecopyresampled($ResampledImage, $this->source, 0, 0, 0, 0,
  114. $NewWidth, $NewHeight, $this->imageW, $this->imageH);
  115.  
  116. return $this->target = $ResampledImage;
  117. }
  118. else return null;
  119. }
  120.  
  121. public function Crop($Width, $Height = 0)
  122. {
  123. if(!$Width && !$Height)
  124. throw new Exception("You Must provide the cropped width or cropped height");
  125. elseif($Width && !$Height) $Height = $Width;
  126.  
  127. $width = $this->getImageWidth();
  128. $height = $this->getImageHeight();
  129.  
  130. $x = round(($width - $Width)/2);
  131. $y = round(($height - $Height)/2);
  132. //
  133. $temp = imagecreatetruecolor($width, $height);
  134. $imgCropped = imagecreatetruecolor($Width, $Height);
  135. //
  136. imagecopy($imgCropped, $this->source, 0, 0, $x, $y-50, $width, $height);
  137. $this->target = $imgCropped;
  138.  
  139.  
  140. if($this->watermark) {
  141. $this->Watermark ();
  142. }
  143. //
  144. return $this->target;
  145. }
  146.  
  147. public function Watermark()
  148. {
  149. if(!$this->watermark) return null;
  150.  
  151. //Set the blending mode and save its alpha
  152. imageAlphaBlending($this->watermark, true);
  153. imageSaveAlpha($this->watermark, true);
  154.  
  155. $watermarkWidth=imageSX($this->watermark);
  156. $watermarkHeight = imageSY($this->watermark);
  157.  
  158. $imageWidth = imagesx($this->target);
  159. $imageHeight = imagesy($this->target);
  160.  
  161. //Make that width = height
  162. if($imageWidth <= $watermarkWidth) {
  163. $watermarkWidth = $imageWidth;
  164. $x = 0;
  165. $y = $imageHeight - $watermarkHeight;
  166. }
  167. elseif($imageWidth > $watermarkWidth) {
  168. $x = $imageWidth - $watermarkWidth;
  169. $y = $imageHeight - $watermarkHeight;
  170. }
  171. // Copy a $watermark to $image
  172. imagecopy($this->target, $this->watermark, $x, $y, 0, 0, $watermarkWidth,
  173. $watermarkHeight);
  174. // Save the copied $image to the $target_file
  175. // end then destroy the $image and $watermark resources
  176. return $this->target;
  177. }
  178. public function Save($asFile = "")
  179. {
  180. if($this->target){
  181. if($this->mime){
  182. switch ($this->mime){
  183. case "image/jpeg":
  184. case "image/jpg":
  185. case "image/pjpeg":
  186. if(empty($asFile)) imagejpeg($this->target, $this->path . DS . $this->filename ,100);
  187. else imagejpeg($this->target, $this->path . DS . $asFile ,100);
  188. break;
  189. case "image/png":
  190. if(empty($asFile)) imagepng($this->target, $this->path . DS . $this->filename ,0);
  191. else imagepng($this->target, $this->path . DS . $asFile ,0);
  192. break;
  193. case "image/gif":
  194. if(empty($asFile)) imagegif($this->target, $this->path . DS . $this->filename ,100);
  195. else imagegif($this->target, $this->path . DS . $asFile ,100);
  196. break;
  197. default : break;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. ?>

 

If you want to test for yourself this great class. You need to include this class in your PHP file and instantiate an object of this, before you can call upon the defined methode and its public properties. For this raison, I've synthesized an PHP example so that you can test it and see its perfomance. You can further extend this class and add your own methods in other to enrich it.

Here is code test:

  1. <?php
  2. require_once 'Image_Processor.class.php';
  3.  
  4. $path_to_save_in = "/folder/";
  5. $img_proc = new Image_Processor($_FILES['file']['tmp_name'], 0, 0, $path_to_save_in);
  6. $img_proc->getImageWidth();
  7. $img_proc->getImageHeight();
  8. $img_proc->Resize(600, 600);
  9. $img_proc->Crop(520,242);
  10. $saveAs = "Filename" . $img_proc->getImageType();
  11. $img_proc->Save($saveAs);
  12. ?>

 

Have you any problem using it? Let tell it! Have fun!

For those who like to see demo of the execution of this ImageProcessor, here above defined, you can browse to this link: Imageprocessor

Available Comments :

Joannes

Apr. 27, 2011 at 02:16 PM

Why don't you write in french?

Emmanuel Ndayiragije

May. 05, 2011 at 04:30 PM

Salut Joannes,
Quand j'ai programmé ce système, je l'ai codé supportant l'englais seulement. Bientôt, je vais l'étendre pour pouvoir supporter d'autres langages(Internationalization & Localization).
Toute fois, merci pour votre commentaire.

Your Attention! Please do not post message with spam on this blog. We try to be cool to each other and post relevant comments and relating to the appropriated topic or entry. Let's try to get a nice conversation over here.

Leave a comment

Required!
Required!

Required!
Required!

Latest News

  • Dec. 22, 2014 at 02:02
    Beji Caid Essebsi claims victory in Tunisia's first free presidential election, with exit polls suggesting he won more than 55% of the vote
    Read more»
  • Dec. 22, 2014 at 01:44
    Street lights are being switched off or dimmed to save money in three quarters of England's council areas, according to Labour Party researc...
    Read more»
  • Dec. 22, 2014 at 01:35
    Watch the latest news summary from BBC World News. International news updated 24 hours a day.
    Read more»
  • Dec. 22, 2014 at 01:19
    The hard side of soft power in China's Confucius institutes
    Read more»
  • Dec. 22, 2014 at 01:06
    Scottish construction firms call for increased funding to help recruit and train more apprentices.
    Read more»
  • Dec. 22, 2014 at 01:06
    The BBC's Richard Taylor tests out a hoverboard that uses magnetic levitation.
    Read more»
  • Dec. 22, 2014 at 01:04
    The Financial Ombudsman Service says it received 2,200 complaints about gadget warranties last year, double that of the previous year.
    Read more»
  • Dec. 22, 2014 at 01:01
    Business lobby group the CBI says half of UK firms plan to expand their workforce next year, with more permanent jobs being created than tem...
    Read more»
  • Dec. 22, 2014 at 01:01
    BBC reporter meets Indonesian tsunami survivor 10 years on
    Read more»
  • Dec. 22, 2014 at 01:00
    The NHS is setting up 11 centres aimed at unlocking the secrets of DNA and developing drugs to target cancer and rare genetic diseases.
    Read more»
  • Dec. 22, 2014 at 00:55
    A stolen laptop containing the last photographs of an ill child before she died is returned to her family.
    Read more»
  • Dec. 22, 2014 at 00:36
    A driver shouting the Islamic phrase "God is great" in Arabic runs down pedestrians in the French city of Dijon, injuring 11, French media s...
    Read more»
  • Dec. 22, 2014 at 00:33
    Sir Elton John and his partner David Furnish have officially married, nine years after they held their civil partnership ceremony.
    Read more»
  • Dec. 22, 2014 at 00:18
    Acclaimed actress Billie Whitelaw, who starred on stage and screen and worked in close collaboration with Samuel Beckett, dies in London.
    Read more»
  • Dec. 22, 2014 at 00:05
    A court in Argentina rules that a shy orangutan who spent the last 20 years in a zoo can be granted some legal rights enjoyed by humans.
    Read more»
  • Dec. 21, 2014 at 23:59
    Spanish champions Atletico Madrid end a remarkable 2014 on a high with a 4-1 comeback win at Athletic Bilbao.
    Read more»
  • Dec. 21, 2014 at 23:01
    Amstrad founder Lord Sugar names Australian businessman Mark Wright as his latest business partner, at the climax of BBC One's The Apprentic...
    Read more»
  • Dec. 21, 2014 at 21:54
    Oil-rich Gulf states vow not to cut crude production, blaming speculators and producers outside the Opec group for falling prices.
    Read more»
  • Dec. 21, 2014 at 20:34
    Sir Elton John and his partner David Furnish convert their civil partnership to a marriage - with the musician documenting the day on the In...
    Read more»
  • Dec. 21, 2014 at 19:52
    Aberdeen City Council announces it is to hold a summit to look at the challenges facing the North Sea oil industry.
    Read more»

Recent Comments:

Pharmb740

Sep. 25, 2014 at 11:59 AM

Very nice site!

Pharmf503

Sep. 25, 2014 at 06:32 AM

Very nice site! cheap goods http://apeyixo2.com/ysyaqqs/4.html

Pharmf80

Sep. 23, 2014 at 06:22 PM

Very nice site!

Pharmf581

Sep. 23, 2014 at 06:22 PM

Very nice site! cheap goods http://aieopxy2.com/osovrrv/4.html

Pharmg443

Sep. 23, 2014 at 06:21 PM

Very nice site! cheap goods

Archives:

Meet me on facebook: