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

  • Jul. 25, 2014 at 10:50
    Suspected Taliban gunmen kill 15 bus passengers from the minority Hazara community in the central Afghan province of Ghor, officials say.
    Read more»
  • Jul. 25, 2014 at 10:44
    The UK economy grew 0.8% in the second quarter and has now recovered the ground lost since the downturn began in 2008, according to official...
    Read more»
  • Jul. 25, 2014 at 10:39
    The National Theatre announces that Of Mice and Men will be their first Broadway production to screen live in UK cinemas.
    Read more»
  • Jul. 25, 2014 at 10:31
    Royal Bank of Scotland says it expects pre-tax profits of £2.65bn for the first half of the year but warns of 'bumps in the road ahead'.
    Read more»
  • Jul. 25, 2014 at 10:17
    Watch the latest news summary from BBC World News. International news updated 24 hours a day.
    Read more»
  • Jul. 25, 2014 at 10:08
    More than 800 people have died in the latest outbreak of violence in the Middle East, and despite calls for a ceasefire, the fighting contin...
    Read more»
  • Jul. 25, 2014 at 10:00
    A pioneering breast cancer treatment that replaces weeks of radiotherapy with a single, targeted shot is set to be offered on the NHS.
    Read more»
  • Jul. 25, 2014 at 09:56
    A group of 157 asylum seekers held at sea will be brought to the Australian mainland to be detained, the immigration minister says.
    Read more»
  • Jul. 25, 2014 at 09:40
    Even dimly lit bedrooms may stop breast cancer drugs from working, according to US research.
    Read more»
  • Jul. 25, 2014 at 09:30
    Star Wars actor Mark Hamill calls returning to the franchise was an "unexpected gift", and says Harrison Ford is recovering well from his br...
    Read more»
  • Jul. 25, 2014 at 09:24
    BSkyB wants to take over Rupert Murdoch's pay TV companies in Germany and Italy in a move that would create a company with 20 million Europe...
    Read more»
  • Jul. 25, 2014 at 09:21
    A new exhibition at Buckingham Palace is revealing what is is like to grow up in the Royal Family.
    Read more»
  • Jul. 25, 2014 at 09:10
    At least two Palestinians die and more than 200 are hurt during West Bank protests against Israel's military operation in Gaza.
    Read more»
  • Jul. 25, 2014 at 09:06
    The wreckage of a plane that disappeared with 116 people on board on a flight from Burkina Faso to Algiers has been found in Mali, officials...
    Read more»
  • Jul. 25, 2014 at 08:25
    Giant marionettes are back on Liverpool's streets as part of a three-day event commemorating World War One.
    Read more»
  • Jul. 25, 2014 at 07:10
    All dinosaurs were covered with feathers or had the potential to grow feathers, a study published in the journal, Science, suggests.
    Read more»
  • Jul. 25, 2014 at 06:41
    China editor Carrie Gracie looks at what's made news this week
    Read more»
  • Jul. 25, 2014 at 06:07
    The US says Russia has fired artillery at Ukrainian military positions in the east, a week after the Malaysia Airlines flight MH17 disaster....
    Read more»
  • Jul. 25, 2014 at 05:58
    South Korea's forensic agency says it cannot determine the cause of death for the fugitive tycoon blamed for the recent ferry disaster.
    Read more»
  • Jul. 25, 2014 at 03:36
    Fast-food chain McDonald's suspends sale of chicken nuggets in Hong Kong over the out of date meat scandal at a Chinese supplier.
    Read more»

Recent Comments:

Ehcjntublr

Jun. 11, 2014 at 06:06 PM

leebvfnnbovfmoebzjsbhjkf, http://www.pykbyrhrlo.com/ spdwthctlr

Natural hair care products

May. 27, 2014 at 09:05 AM

These are really great ideas in on the topic of blogging. You have touched some pleasant things here. Any way keep up wrinting.

Remedies for piles

May. 18, 2014 at 05:44 PM

Thanks for finally writing about > %blog_title% < Loved it!

Website

Mar. 25, 2014 at 08:19 PM

There are books, home study courses, workshops and other means of information, to gain the knowledge required to become the alpha leader. If you want ... Read more»

Titia

Feb. 15, 2014 at 01:48 AM

buy car insurance online prozac 40mg no rx best deals on vigra and cialis website auto insurance quoye www.evansvillecommunitytheatre.com ... Read more»

Archives:

Meet me on facebook: