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

  • Sep. 21, 2014 at 22:00
    The Yemeni government and Shia Houthi rebels sign an agreement aimed at ending the political crisis which has gripped the country for weeks....
    Read more»
  • Sep. 21, 2014 at 21:54
    Street protests demanding urgent action on climate change have been taking place around the world, with marches reported in more than 2,000 ...
    Read more»
  • Sep. 21, 2014 at 21:49
    The Peruvian authorities announce a new anti-logging commission after the killings of four indigenous leaders in the Amazon rainforest.
    Read more»
  • Sep. 21, 2014 at 21:24
    Thousands of people take part in marches for climate action in London and across the UK, ahead of a UN summit in New York on Tuesday.
    Read more»
  • Sep. 21, 2014 at 20:19
    The Duke of Cambridge plays table football as he meets teenagers during a visit to Malta to celebrate the country's 50 years of independence...
    Read more»
  • Sep. 21, 2014 at 19:50
    Engineers have invented a battery made of three liquefied metals, which they say is efficient and cheap enough to store power on the electri...
    Read more»
  • Sep. 21, 2014 at 19:42
    New research shows China's rising emissions per head of population have overtaken the EU while the global total reaches a new high.
    Read more»
  • Sep. 21, 2014 at 19:38
    Latvian police say a convicted murderer wanted over the disappearance of Alice Gross from London could be in the eastern European country - ...
    Read more»
  • Sep. 21, 2014 at 19:36
    Manchester United let a 3-1 lead slip as Leicester City fight back to secure a stunning victory at the King Power Stadium.
    Read more»
  • Sep. 21, 2014 at 19:13
    The fate of Air France is "at stake" in a dispute between Air France and its pilots, according to France's Transport Minister.
    Read more»
  • Sep. 21, 2014 at 19:02
    Tens of thousands of people attend a Mass by Pope Francis, as the pontiff hits out at extremists "perverting" religion to justify violence.
    Read more»
  • Sep. 21, 2014 at 18:51
    Downing Street insists it will not backtrack on its devolution pledge to Scotland despite Tory calls for swift action on more powers for Eng...
    Read more»
  • Sep. 21, 2014 at 18:33
    Kenya is marking a year since the attack by Islamist militants on Nairobi's Westgate shopping centre, in which at least 67 people were kille...
    Read more»
  • Sep. 21, 2014 at 17:34
    Tens of thousands of Russians are marching in Moscow in protest against Russia's involvement in the Ukraine crisis.
    Read more»
  • Sep. 21, 2014 at 16:59
    Lewis Hamilton leads the World Championship after victory in the Singapore Grand Prix as Nico Rosberg retires.
    Read more»
  • Sep. 21, 2014 at 16:48
    A global initiative is launched to get people and choirs from around the world singing together for peace.
    Read more»
  • Sep. 21, 2014 at 16:25
    A deal to form a unity government in Afghanistan has been signed at a televised ceremony in Kabul, ending months of political wrangling.
    Read more»
  • Sep. 21, 2014 at 16:25
    The family of murdered British tourist Hannah Witheridge say they are "broken" after she was found murdered on a Thai island.
    Read more»
  • Sep. 21, 2014 at 16:23
    The US Treasury Secretary urges eurozone countries to "boost demand" in order to reduce unemployment and avoid deflation.
    Read more»
  • Sep. 21, 2014 at 15:05
    A military aircraft has crashed in Egypt, killing six crew, state TV reports.
    Read more»

Recent Comments:

Pharma712

Sep. 21, 2014 at 02:39 AM

Very nice site! cheap goods

Pharmd10

Sep. 19, 2014 at 07:03 PM

Very nice site!

Pharmc274

Sep. 19, 2014 at 07:01 PM

Very nice site! [url=http://opxyiea2.com/yoyaqqo/2.html]cheap goods[/url]

Pharmd689

Sep. 18, 2014 at 12:36 PM

Very nice site! [url=http://oixypea2.com/qxqsxxq/2.html]cheap goods[/url]

Pharma24

Sep. 18, 2014 at 12:35 PM

Very nice site! cheap goods

Archives:

Meet me on facebook: