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

  • Oct. 26, 2014 at 00:42
    Kurdish and Iraqi forces say they have gained ground from Islamic State militants in northern Iraq and near Baghdad, amid intense US-led air...
    Read more»
  • Oct. 26, 2014 at 00:40
    At least six Lebanese soldiers have died in clashes with Islamist gunmen at a historic market in the northern town of Tripoli, the army says...
    Read more»
  • Oct. 26, 2014 at 00:34
    Police attend an incident in the centre of Edinburgh, amid reports that an armed man is on a roof.
    Read more»
  • Oct. 25, 2014 at 23:21
    An IT problem at Heathrow airport causes baggage handling problems, with some passengers reporting "huge delays".
    Read more»
  • Oct. 25, 2014 at 23:15
    Tens of thousands of parents in Chile march against the government's planned education bill which would phase out subsidised schools.
    Read more»
  • Oct. 25, 2014 at 22:23
    Watch the latest news summary from BBC World News. International news updated 24 hours a day.
    Read more»
  • Oct. 25, 2014 at 22:15
    British journalist John Cantlie, who is being held captive by Islamic State militants, is shown reading a message in a new propaganda video ...
    Read more»
  • Oct. 25, 2014 at 20:28
    Real Madrid take the Clasico honours as they beat arch-rivals Barcelona in a captivating game at the Bernabeu.
    Read more»
  • Oct. 25, 2014 at 20:04
    Four tries from Wales wing George North see Saints end Ospreys' unbeaten start to the season in the Champions Cup.
    Read more»
  • Oct. 25, 2014 at 19:40
    Scottish Labour leader Johann Lamont resigns saying senior party members had "questioned" her role amid the "serious challenges" faced by La...
    Read more»
  • Oct. 25, 2014 at 19:36
    After experimenting with permanent summer hours, Russia is adopting permanent winter hours due to fewer hours of daylight in the north.
    Read more»
  • Oct. 25, 2014 at 18:19
    Iran hangs a woman who killed a man she said was trying to sexually abuse her, drawing protests from human rights groups and western countri...
    Read more»
  • Oct. 25, 2014 at 18:05
    The rest of Europe expects the UK to settle a £1.7bn EU budget demand "and that's that", a vice president of the European Parliament has sa...
    Read more»
  • Oct. 25, 2014 at 18:04
    Scuffles break out as South Korean residents try to prevent activists sending balloons into the North carrying anti-government leaflets.
    Read more»
  • Oct. 25, 2014 at 17:22
    Scottish musician Jack Bruce, the bassist and singer with 1960s supergroup Cream, dies aged 71, his publicist confirms.
    Read more»
  • Oct. 25, 2014 at 17:13
    India's arm's length PM mixes with reporters - a bit
    Read more»
  • Oct. 25, 2014 at 17:03
    The US urges an investigation after an Palestinian-American teenager is shot dead by Israeli soldiers near Ramallah in the West Bank.
    Read more»
  • Oct. 25, 2014 at 17:00
    The number of cases in the Ebola outbreak passes 10,000, with 4,922 deaths, the World Health Organization's latest report says.
    Read more»
  • Oct. 25, 2014 at 16:06
    Former Olympic 800m silver medallist Mbulaeni Mulaudzi is killed in a road traffic accident in his native South Africa.
    Read more»
  • Oct. 25, 2014 at 16:04
    A mass protest is held in the Italian capital, Rome, against Prime Minister Matteo Renzi's plans for labour market reform.
    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: