imagemagick.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. class Image_Imagemagick extends \Image_Driver
  14. {
  15. protected $image_temp = null;
  16. protected $accepted_extensions = array('png', 'gif', 'jpg', 'jpeg');
  17. protected $size_cache = null;
  18. protected $im_path = null;
  19. public function load($filename, $return_data = false, $force_extension = false)
  20. {
  21. extract(parent::load($filename, $return_data, $force_extension));
  22. $this->clear_sizes();
  23. if (empty($this->image_temp))
  24. {
  25. do
  26. {
  27. $this->image_temp = $this->config['temp_dir'].substr($this->config['temp_append'].md5(time() * microtime()), 0, 32).'.png';
  28. }
  29. while (file_exists($this->image_temp));
  30. }
  31. elseif (file_exists($this->image_temp))
  32. {
  33. $this->debug('Removing previous temporary image.');
  34. unlink($this->image_temp);
  35. }
  36. $this->debug('Temp file: '.$this->image_temp);
  37. if (!file_exists($this->config['temp_dir']) || !is_dir($this->config['temp_dir']))
  38. {
  39. throw new \RuntimeException("The temp directory that was given does not exist.");
  40. }
  41. elseif (!touch($this->config['temp_dir'] . $this->config['temp_append'] . '_touch'))
  42. {
  43. throw new \RuntimeException("Could not write in the temp directory.");
  44. }
  45. $this->exec('convert', '"'.$image_fullpath.'"[0] "'.$this->image_temp.'"');
  46. return $this;
  47. }
  48. protected function _crop($x1, $y1, $x2, $y2)
  49. {
  50. extract(parent::_crop($x1, $y1, $x2, $y2));
  51. $image = '"'.$this->image_temp.'"';
  52. $this->exec('convert', $image.' -crop '.($x2 - $x1).'x'.($y2 - $y1).'+'.$x1.'+'.$y1.' +repage '.$image);
  53. $this->clear_sizes();
  54. }
  55. protected function _resize($width, $height = null, $keepar = true, $pad = true)
  56. {
  57. extract(parent::_resize($width, $height, $keepar, $pad));
  58. $image = '"'.$this->image_temp.'"';
  59. $this->exec('convert', "-define png:size=".$cwidth."x".$cheight." ".$image." ".
  60. "-background none ".
  61. "-resize \"".($pad ? $width : $cwidth)."x".($pad ? $height : $cheight)."!\" ".
  62. "-gravity center ".
  63. "-extent ".$cwidth."x".$cheight." ".$image);
  64. $this->clear_sizes();
  65. }
  66. protected function _rotate($degrees)
  67. {
  68. extract(parent::_rotate($degrees));
  69. $image = '"'.$this->image_temp.'"';
  70. $this->exec('convert', $image." -background none -virtual-pixel background +distort ScaleRotateTranslate ".$degrees." +repage ".$image);
  71. $this->clear_sizes();
  72. }
  73. protected function _flip($direction)
  74. {
  75. switch ($direction)
  76. {
  77. case 'vertical':
  78. $arg = '-flip';
  79. break;
  80. case 'horizontal':
  81. $arg = '-flop';
  82. break;
  83. case 'both':
  84. $arg = '-flip -flop';
  85. break;
  86. default: return false;
  87. }
  88. $image = '"'.$this->image_temp.'"';
  89. $this->exec('convert', $image.' '.$arg.' '.$image);
  90. }
  91. protected function _watermark($filename, $position, $padding = 5)
  92. {
  93. $values = parent::_watermark($filename, $position, $padding);
  94. if ($values == false)
  95. {
  96. throw new \InvalidArgumentException("Watermark image not found or invalid filetype.");
  97. }
  98. extract($values);
  99. $x >= 0 and $x = '+'.$x;
  100. $y >= 0 and $y = '+'.$y;
  101. $this->exec(
  102. 'composite',
  103. '-compose atop -geometry '.$x.$y.' '.
  104. '-dissolve '.$this->config['watermark_alpha'].'% '.
  105. '"'.$filename.'" "'.$this->image_temp.'" '.$image
  106. );
  107. }
  108. protected function _border($size, $color = null)
  109. {
  110. extract(parent::_border($size, $color));
  111. $image = '"'.$this->image_temp.'"';
  112. $color = $this->create_color($color, 100);
  113. $command = $image.' -compose copy -bordercolor '.$color.' -border '.$size.'x'.$size.' '.$image;
  114. $this->exec('convert', $command);
  115. $this->clear_sizes();
  116. }
  117. protected function _mask($maskimage)
  118. {
  119. extract(parent::_mask($maskimage));
  120. $mimage = '"'.$maskimage.'"';
  121. $image = '"'.$this->image_temp.'"';
  122. $command = $image.' '.$mimage.' +matte -compose copy-opacity -composite '.$image;
  123. $this->exec('convert', $command);
  124. }
  125. /**
  126. * Credit to Leif Åstrand <[email protected]> for the base of the round corners.
  127. *
  128. * Note there is a defect with this, as non-transparent corners get opaque circles of color. Maybe mask it with auto-generated corners?
  129. *
  130. * @link http://www.imagemagick.org/Usage/thumbnails/#rounded
  131. */
  132. protected function _rounded($radius, $sides, $antialias = 0)
  133. {
  134. extract(parent::_rounded($radius, $sides, null));
  135. $image = '"'.$this->image_temp.'"';
  136. $r = $radius;
  137. $command = $image." ( +clone -alpha extract ".
  138. ( ! $tr ? '' : "-draw \"fill black polygon 0,0 0,$r $r,0 fill white circle $r,$r $r,0\" ")."-flip ".
  139. ( ! $br ? '' : "-draw \"fill black polygon 0,0 0,$r $r,0 fill white circle $r,$r $r,0\" ")."-flop ".
  140. ( ! $bl ? '' : "-draw \"fill black polygon 0,0 0,$r $r,0 fill white circle $r,$r $r,0\" ")."-flip ".
  141. ( ! $tl ? '' : "-draw \"fill black polygon 0,0 0,$r $r,0 fill white circle $r,$r $r,0\" ").
  142. ') -alpha off -compose CopyOpacity -composite '.$image;
  143. $this->exec('convert', $command);
  144. }
  145. protected function _grayscale()
  146. {
  147. $image = '"'.$this->image_temp.'"';
  148. $this->exec('convert', $image." -colorspace Gray ".$image);
  149. }
  150. public function sizes($filename = null, $usecache = true)
  151. {
  152. $is_loaded_file = $filename == null;
  153. if ( ! $is_loaded_file or $this->sizes_cache == null or !$usecache)
  154. {
  155. $reason = ($filename != null ? "filename" : ($this->size_cache == null ? 'cache' : 'option'));
  156. $this->debug("Generating size of image... (triggered by $reason)");
  157. if ($is_loaded_file and ! empty($this->image_temp))
  158. {
  159. $filename = $this->image_temp;
  160. }
  161. $output = $this->exec('identify', '-format "%[fx:w] %[fx:h]" "'.$filename.'"[0]');
  162. list($width, $height) = explode(" ", $output[0]);
  163. $return = (object) array(
  164. 'width' => $width,
  165. 'height' => $height
  166. );
  167. if ($is_loaded_file)
  168. {
  169. $this->sizes_cache = $return;
  170. }
  171. $this->debug("Sizes ".( !$is_loaded_file ? "for <code>$filename</code> " : "")."are now $width and $height");
  172. }
  173. else
  174. {
  175. $return = $this->sizes_cache;
  176. }
  177. return $return;
  178. }
  179. public function save($filename, $permissions = null)
  180. {
  181. extract(parent::save($filename, $permissions));
  182. $this->run_queue();
  183. $this->add_background();
  184. $filetype = $this->image_extension;
  185. $old = '"'.$this->image_temp.'"';
  186. $new = '"'.$filename.'"';
  187. if(($filetype == 'jpeg' or $filetype == 'jpg') and $this->config['quality'] != 100)
  188. {
  189. $quality = '"'.$this->config['quality'].'%"';
  190. $this->exec('convert', $old.' -quality '.$quality.' '.$new);
  191. }
  192. else
  193. {
  194. $this->exec('convert', $old.' '.$new);
  195. }
  196. if ($this->config['persistence'] === false)
  197. {
  198. $this->reload();
  199. }
  200. return $this;
  201. }
  202. public function output($filetype = null)
  203. {
  204. extract(parent::output($filetype));
  205. $this->run_queue();
  206. $this->add_background();
  207. $image = '"'.$this->image_temp.'"';
  208. if(($filetype == 'jpeg' or $filetype == 'jpg') and $this->config['quality'] != 100)
  209. {
  210. $quality = '"'.$this->config['quality'].'%"';
  211. $this->exec('convert', $image.' -quality '.$quality.' '.strtolower($filetype).':-', true);
  212. }
  213. elseif (substr($this->image_temp, -1 * strlen($filetype)) != $filetype)
  214. {
  215. if ( ! $this->config['debug'])
  216. {
  217. $this->exec('convert', $image.' '.strtolower($filetype).':-', true);
  218. }
  219. }
  220. else
  221. {
  222. if ( ! $this->config['debug'])
  223. {
  224. echo file_get_contents($this->image_temp);
  225. }
  226. }
  227. if ($this->config['persistence'] === false)
  228. {
  229. $this->reload();
  230. }
  231. return $this;
  232. }
  233. /**
  234. * Cleared the currently loaded sizes, used to removed cached sizes.
  235. */
  236. protected function clear_sizes()
  237. {
  238. $this->sizes_cache = null;
  239. }
  240. protected function add_background()
  241. {
  242. if ($this->config['bgcolor'] != null)
  243. {
  244. $bgcolor = $this->config['bgcolor'] == null ? '#000' : $this->config['bgcolor'];
  245. $image = '"'.$this->image_temp.'"';
  246. $color = $this->create_color($bgcolor, 100);
  247. $sizes = $this->sizes();
  248. $command = '-size '.$sizes->width.'x'.$sizes->height.' '.'canvas:'.$color.' '.
  249. $image.' -composite '.$image;
  250. $this->exec('convert', $command);
  251. }
  252. }
  253. /**
  254. * Executes the specified imagemagick executable and returns the output.
  255. *
  256. * @param string $program The name of the executable.
  257. * @param string $params The parameters of the executable.
  258. * @param boolean $passthru Returns the output if false or pass it to browser.
  259. * @return mixed Either returns the output or returns nothing.
  260. */
  261. private function exec($program, $params, $passthru = false)
  262. {
  263. // Determine the path
  264. $this->im_path = realpath($this->config['imagemagick_dir'].$program);
  265. if ( ! $this->im_path)
  266. {
  267. $this->im_path = realpath($this->config['imagemagick_dir'].$program.'.exe');
  268. }
  269. if ( ! $this->im_path)
  270. {
  271. throw new \RuntimeException("imagemagick executables not found in ".$this->config['imagemagick_dir']);
  272. }
  273. $command = $this->im_path." ".$params;
  274. $this->debug("Running command: <code>$command</code>");
  275. $code = 0;
  276. $output = null;
  277. $passthru ? passthru($command) : exec($command, $output, $code);
  278. if ($code != 0)
  279. {
  280. throw new \FuelException("imagemagick failed to edit the image. Returned with $code.<br /><br />Command:\n <code>$command</code>");
  281. }
  282. return $output;
  283. }
  284. /**
  285. * Creates a new color usable by ImageMagick.
  286. *
  287. * @param string $hex The hex code of the color
  288. * @param integer $alpha The alpha of the color, 0 (trans) to 100 (opaque)
  289. * @return string rgba representation of the hex and alpha values.
  290. */
  291. protected function create_color($hex, $alpha)
  292. {
  293. extract($this->create_hex_color($hex));
  294. return "\"rgba(".$red.", ".$green.", ".$blue.", ".round($alpha / 100, 2).")\"";
  295. }
  296. public function __destruct()
  297. {
  298. if (file_exists($this->image_temp))
  299. {
  300. unlink($this->image_temp);
  301. }
  302. }
  303. }