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

  • Apr. 20, 2014 at 15:06
    Ofsted chief Sir Michael Wilshaw is to take personal charge of the watchdog's investigation into claims that a number of schools in Birmingh...
    Read more»
  • Apr. 20, 2014 at 14:52
    Liverpool open up a five-point lead at the top of the Premier League after a hard-fought win over relegation-battling Norwich.
    Read more»
  • Apr. 20, 2014 at 14:41
    The search for three Sherpa guides, missing after an avalanche on Mount Everest killed 13 of their colleagues, is called off.
    Read more»
  • Apr. 20, 2014 at 14:01
    The Archbishop of Canterbury highlights the suffering of people in conflicts around the world during his Easter Sunday sermon.
    Read more»
  • Apr. 20, 2014 at 13:46
    Pope Francis celebrates Easter in front of thousands in St Peter's Square, praying for peace in Syria and Ukraine and "an end to all war".
    Read more»
  • Apr. 20, 2014 at 13:38
    Newsreader George Alagiah says he has been "strengthened" by people's messages after revealing he has bowel cancer.
    Read more»
  • Apr. 20, 2014 at 13:35
    Jack White records and cuts a single in four hours, and claims a world record has been broken.
    Read more»
  • Apr. 20, 2014 at 13:34
    A businessman appointed by the prime minister to head a multibillion-pound quango steps down after it was revealed that he was bankrupt.
    Read more»
  • Apr. 20, 2014 at 13:28
    Islamist militants have killed 11 Algerian soldiers in an ambush on a patrol in mountains east of the capital Algiers, security sources say....
    Read more»
  • Apr. 20, 2014 at 13:22
    Samuel L Jackson, Bruce Dern and Michael Madsen join Quentin Tarantino for a live reading of a leaked, unproduced film script.
    Read more»
  • Apr. 20, 2014 at 13:16
    Russian media is reporting that up to 5 people were killed after gunmen attacked a checkpoint manned by pro-Russian activists near Sloviansk...
    Read more»
  • Apr. 20, 2014 at 13:08
    The Russian foreign ministry expresses outrage at a fatal shooting incident in eastern Ukraine which it blames on Ukrainian nationalists.
    Read more»
  • Apr. 20, 2014 at 12:50
    The pope has prayed for an end to conflicts around the world including in Syria and Ukraine, in his Easter address.
    Read more»
  • Apr. 20, 2014 at 12:48
    The NASUWT teachers' union warns of industrial action in the run up to next year's general election.
    Read more»
  • Apr. 20, 2014 at 12:43
    Families of passengers on a sunken South Korean ferry protest angrily over the rescue operation, scuffling with police on Jindo island.
    Read more»
  • Apr. 20, 2014 at 12:21
    The Duke and Duchess of Cambridge attend an Easter Sunday church service in Sydney and take Prince George to the zoo as part of their overse...
    Read more»
  • Apr. 20, 2014 at 12:11
    Four French journalists who spent 10 months in captivity in Syria were chained to each other and kept in basements without light, one recoun...
    Read more»
  • Apr. 20, 2014 at 10:46
    Lewis Hamilton takes a dominant victory in the Chinese GP to win three consecutive races for the first time in his career.
    Read more»
  • Apr. 20, 2014 at 10:28
    Scottish government agencies Scottish Enterprise and Visit Scotland have quit business lobby organisation CBI after it formally backed the c...
    Read more»
  • Apr. 20, 2014 at 09:03
    Orthodox Christians in Ukraine are celebrating Easter although the situation in the country remains unstable.
    Read more»

Recent Comments:

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»

Cheap online prescription glasses

Jun. 27, 2012 at 03:47 PM

I was suggested this blog by my cousin. I am not sure whether this post is
written by him as nobody else know such detailed about my difficulty.<... Read more»

Emmanuel

Jun. 23, 2012 at 04:02 PM

This article is about the awesome HTML 5 video feature which takes time for web developers to build up web video portals, gjust like does youtube. Wit... Read more»

Oil water separators

Jun. 21, 2012 at 12:37 PM

For the reason that the admin of this website is working,
no hesitation very rapidly it will be renowned, due
to its quality contents.

Archives:

Meet me on facebook: