Editor.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. <?php
  2. namespace Grafika\Imagick;
  3. use Grafika\DrawingObjectInterface;
  4. use Grafika\EditorInterface;
  5. use Grafika\FilterInterface;
  6. use Grafika\Grafika;
  7. use Grafika\ImageInterface;
  8. use Grafika\ImageType;
  9. use Grafika\Color;
  10. use Grafika\Imagick\ImageHash\DifferenceHash;
  11. use Grafika\Position;
  12. /**
  13. * Imagick Editor class. Uses the PHP Imagick library.
  14. * @package Grafika\Imagick
  15. */
  16. final class Editor implements EditorInterface
  17. {
  18. /**
  19. * Apply a filter to the image. See Filters section for a list of available filters.
  20. *
  21. * @param Image $image
  22. * @param FilterInterface $filter
  23. *
  24. * @return Editor
  25. */
  26. public function apply(&$image, $filter)
  27. {
  28. if ($image->isAnimated()) { // Ignore animated GIF for now
  29. return $this;
  30. }
  31. $image = $filter->apply($image);
  32. return $this;
  33. }
  34. /**
  35. * Blend two images together with the first image as the base and the second image on top. Supports several blend modes.
  36. *
  37. * @param Image $image1 The base image.
  38. * @param Image $image2 The image placed on top of the base image.
  39. * @param string $type The blend mode. Can be: normal, multiply, overlay or screen.
  40. * @param float $opacity The opacity of $image2. Possible values 0.0 to 1.0 where 0.0 is fully transparent and 1.0 is fully opaque. Defaults to 1.0.
  41. * @param string $position The position of $image2 on $image1. Possible values top-left, top-center, top-right, center-left, center, center-right, bottom-left, bottom-center, bottom-right and smart. Defaults to top-left.
  42. * @param int $offsetX Number of pixels to add to the X position of $image2.
  43. * @param int $offsetY Number of pixels to add to the Y position of $image2.
  44. *
  45. * @return Editor
  46. * @throws \Exception When added image is outside of canvas or invalid blend type
  47. */
  48. public function blend(&$image1, $image2, $type='normal', $opacity = 1.0, $position = 'top-left', $offsetX = 0, $offsetY = 0 ){
  49. // Turn into position object
  50. $position = new Position($position, $offsetX, $offsetY);
  51. // Position is for $image2. $image1 is canvas.
  52. list($offsetX, $offsetY) = $position->getXY($image1->getWidth(), $image1->getHeight(), $image2->getWidth(), $image2->getHeight());
  53. // Check if it overlaps
  54. if( ($offsetX >= $image1->getWidth() ) or
  55. ($offsetX + $image2->getWidth() <= 0) or
  56. ($offsetY >= $image1->getHeight() ) or
  57. ($offsetY + $image2->getHeight() <= 0)){
  58. throw new \Exception('Invalid blending. Image 2 is outside the canvas.');
  59. }
  60. // Loop start X
  61. $loopStartX = 0;
  62. $canvasStartX = $offsetX;
  63. if($canvasStartX < 0){
  64. $diff = 0 - $canvasStartX;
  65. $loopStartX += $diff;
  66. }
  67. // Loop start Y
  68. $loopStartY = 0;
  69. $canvasStartY = $offsetY;
  70. if($canvasStartY < 0){
  71. $diff = 0 - $canvasStartY;
  72. $loopStartY += $diff;
  73. }
  74. if ( $opacity !== 1 ) {
  75. $this->opacity($image2, $opacity);
  76. }
  77. $type = strtolower( $type );
  78. if($type==='normal') {
  79. $image1->getCore()->compositeImage($image2->getCore(), \Imagick::COMPOSITE_OVER, $loopStartX + $offsetX, $loopStartY + $offsetY);
  80. } else if($type==='multiply'){
  81. $image1->getCore()->compositeImage($image2->getCore(), \Imagick::COMPOSITE_MULTIPLY, $loopStartX + $offsetX, $loopStartY + $offsetY);
  82. } else if($type==='overlay'){
  83. $image1->getCore()->compositeImage($image2->getCore(), \Imagick::COMPOSITE_OVERLAY, $loopStartX + $offsetX, $loopStartY + $offsetY);
  84. } else if($type==='screen'){
  85. $image1->getCore()->compositeImage($image2->getCore(), \Imagick::COMPOSITE_SCREEN, $loopStartX + $offsetX, $loopStartY + $offsetY);
  86. } else {
  87. throw new \Exception(sprintf('Invalid blend type "%s".', $type));
  88. }
  89. return $this;
  90. }
  91. /**
  92. * Compare two images and returns a hamming distance. A value of 0 indicates a likely similar picture. A value between 1 and 10 is potentially a variation. A value greater than 10 is likely a different image.
  93. *
  94. * @param ImageInterface|string $image1
  95. * @param ImageInterface|string $image2
  96. *
  97. * @return int Hamming distance. Note: This breaks the chain if you are doing fluent api calls as it does not return an Editor.
  98. * @throws \Exception
  99. */
  100. public function compare($image1, $image2)
  101. {
  102. if (is_string($image1)) { // If string passed, turn it into a Image object
  103. $image1 = Image::createFromFile($image1);
  104. $this->flatten( $image1 );
  105. }
  106. if (is_string($image2)) { // If string passed, turn it into a Image object
  107. $image2 = Image::createFromFile($image2);
  108. $this->flatten( $image2 );
  109. }
  110. $hash = new DifferenceHash();
  111. $bin1 = $hash->hash($image1, $this);
  112. $bin2 = $hash->hash($image2, $this);
  113. $str1 = str_split($bin1);
  114. $str2 = str_split($bin2);
  115. $distance = 0;
  116. foreach ($str1 as $i => $char) {
  117. if ($char !== $str2[$i]) {
  118. $distance++;
  119. }
  120. }
  121. return $distance;
  122. }
  123. /**
  124. * Crop the image to the given dimension and position.
  125. *
  126. * @param Image $image
  127. * @param int $cropWidth Crop width in pixels.
  128. * @param int $cropHeight Crop Height in pixels.
  129. * @param string $position The crop position. Possible values top-left, top-center, top-right, center-left, center, center-right, bottom-left, bottom-center, bottom-right and smart. Defaults to center.
  130. * @param int $offsetX Number of pixels to add to the X position of the crop.
  131. * @param int $offsetY Number of pixels to add to the Y position of the crop.
  132. *
  133. * @return Editor
  134. * @throws \Exception
  135. */
  136. public function crop(&$image, $cropWidth, $cropHeight, $position = 'center', $offsetX = 0, $offsetY = 0)
  137. {
  138. if ($image->isAnimated()) { // Ignore animated GIF for now
  139. return $this;
  140. }
  141. if ( 'smart' === $position ) { // Smart crop
  142. list( $x, $y ) = $this->_smartCrop( $image, $cropWidth, $cropHeight );
  143. } else {
  144. // Turn into an instance of Position
  145. $position = new Position( $position, $offsetX, $offsetY );
  146. // Crop position as x,y coordinates
  147. list( $x, $y ) = $position->getXY( $image->getWidth(), $image->getHeight(), $cropWidth, $cropHeight );
  148. }
  149. $image->getCore()->cropImage($cropWidth, $cropHeight, $x, $y);
  150. return $this;
  151. }
  152. /**
  153. * Draw a DrawingObject on the image. See Drawing Objects section.
  154. *
  155. * @param Image $image
  156. * @param DrawingObjectInterface $drawingObject
  157. *
  158. * @return $this
  159. */
  160. public function draw(&$image, $drawingObject)
  161. {
  162. if ($image->isAnimated()) { // Ignore animated GIF for now
  163. return $this;
  164. }
  165. $image = $drawingObject->draw($image);
  166. return $this;
  167. }
  168. /**
  169. * Compare if two images are equal. It will compare if the two images are of the same width and height. If the dimensions differ, it will return false. If the dimensions are equal, it will loop through each pixels. If one of the pixel don't match, it will return false. The pixels are compared using their RGB (Red, Green, Blue) values.
  170. *
  171. * @param string|ImageInterface $image1 Can be an instance of Image or string containing the file system path to image.
  172. * @param string|ImageInterface $image2 Can be an instance of Image or string containing the file system path to image.
  173. *
  174. * @return bool True if equals false if not. Note: This breaks the chain if you are doing fluent api calls as it does not return an Editor.
  175. * @throws \Exception
  176. */
  177. public function equal($image1, $image2)
  178. {
  179. if (is_string($image1)) { // If string passed, turn it into a Image object
  180. $image1 = Image::createFromFile($image1);
  181. $this->flatten( $image1 );
  182. }
  183. if (is_string($image2)) { // If string passed, turn it into a Image object
  184. $image2 = Image::createFromFile($image2);
  185. $this->flatten( $image2 );
  186. }
  187. // Check if image dimensions are equal
  188. if ($image1->getWidth() !== $image2->getWidth() or $image1->getHeight() !== $image2->getHeight()) {
  189. return false;
  190. } else {
  191. // Loop using image1
  192. $pixelIterator = $image1->getCore()->getPixelIterator();
  193. foreach ($pixelIterator as $row => $pixels) { /* Loop through pixel rows */
  194. foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
  195. /**
  196. * Get image1 pixel
  197. * @var $pixel \ImagickPixel
  198. */
  199. $rgba1 = $pixel->getColor();
  200. // Get image2 pixel
  201. $rgba2 = $image2->getCore()->getImagePixelColor($column, $row)->getColor();
  202. // Compare pixel value
  203. if (
  204. $rgba1['r'] !== $rgba2['r'] or
  205. $rgba1['g'] !== $rgba2['g'] or
  206. $rgba1['b'] !== $rgba2['b']
  207. ) {
  208. return false;
  209. }
  210. }
  211. $pixelIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
  212. }
  213. }
  214. return true;
  215. }
  216. /**
  217. * Fill entire image with color.
  218. *
  219. * @param Image $image
  220. * @param Color $color Color object
  221. * @param int $x X-coordinate of start point
  222. * @param int $y Y-coordinate of start point
  223. *
  224. * @return self
  225. */
  226. public function fill(&$image, $color, $x = 0, $y = 0)
  227. {
  228. if ($image->isAnimated()) { // Ignore animated GIF for now
  229. return $this;
  230. }
  231. $target = $image->getCore()->getImagePixelColor($x, $y);
  232. $image->getCore()->floodfillPaintImage($color->getHexString(), 1, $target, $x, $y, false);
  233. return $this;
  234. }
  235. /**
  236. * Flatten if animated GIF. Do nothing otherwise.
  237. *
  238. * @param Image $image
  239. *
  240. * @return self
  241. */
  242. public function flatten(&$image){
  243. if($image->isAnimated()){
  244. $imagick = $image->getCore()->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
  245. $image = new Image(
  246. $imagick,
  247. $image->getImageFile(),
  248. $image->getWidth(),
  249. $image->getHeight(),
  250. $image->getType(),
  251. '', // blocks
  252. false // animated
  253. );
  254. }
  255. return $this;
  256. }
  257. /**
  258. * Flip or mirrors the image.
  259. *
  260. * @param Image $image
  261. * @param string $mode The type of flip: 'h' for horizontal flip or 'v' for vertical.
  262. *
  263. * @return Editor
  264. * @throws \Exception
  265. */
  266. public function flip(&$image, $mode){
  267. if ($mode === 'h') {
  268. $image->getCore()->flopImage();
  269. } else if ($mode === 'v') {
  270. $image->getCore()->flipImage();
  271. } else {
  272. throw new \Exception(sprintf('Unsupported mode "%s"', $mode));
  273. }
  274. return $this;
  275. }
  276. /**
  277. * Free the image clearing resources associated with it.
  278. *
  279. * @param Image $image
  280. *
  281. * @return Editor
  282. */
  283. public function free( &$image )
  284. {
  285. $image->getCore()->clear();
  286. return $this;
  287. }
  288. /**
  289. * Checks if the editor is available on the current PHP install.
  290. *
  291. * @return bool True if available false if not.
  292. */
  293. public function isAvailable()
  294. {
  295. // First, test Imagick's extension and classes.
  296. if (false === extension_loaded('imagick') ||
  297. false === class_exists('Imagick') ||
  298. false === class_exists('ImagickDraw') ||
  299. false === class_exists('ImagickPixel') ||
  300. false === class_exists('ImagickPixelIterator')
  301. ) {
  302. return false;
  303. }
  304. return true;
  305. }
  306. /**
  307. * Sets the image to the specified opacity level where 1.0 is fully opaque and 0.0 is fully transparent.
  308. *
  309. * @param Image $image
  310. * @param float $opacity
  311. *
  312. * @return self
  313. * @throws \Exception
  314. */
  315. public function opacity(&$image, $opacity)
  316. {
  317. if ($image->isAnimated()) { // Ignore animated GIF for now
  318. return $this;
  319. }
  320. // Bounds checks
  321. $opacity = ($opacity > 1) ? 1 : $opacity;
  322. $opacity = ($opacity < 0) ? 0 : $opacity;
  323. $image->getCore()->setImageOpacity($opacity);
  324. return $this;
  325. }
  326. /**
  327. * Open an image file and assign Image to first parameter.
  328. *
  329. * @param Image $image
  330. * @param string $imageFile
  331. *
  332. * @return Editor
  333. */
  334. public function open(&$image, $imageFile){
  335. $image = Image::createFromFile( $imageFile );
  336. return $this;
  337. }
  338. /**
  339. * Wrapper function for the resizeXXX family of functions. Resize image given width, height and mode.
  340. *
  341. * @param Image $image
  342. * @param int $newWidth Width in pixels.
  343. * @param int $newHeight Height in pixels.
  344. * @param string $mode Resize mode. Possible values: "exact", "exactHeight", "exactWidth", "fill", "fit".
  345. *
  346. * @return Editor
  347. * @throws \Exception
  348. */
  349. public function resize(&$image, $newWidth, $newHeight, $mode = 'fit')
  350. {
  351. /*
  352. * Resize formula:
  353. * ratio = w / h
  354. * h = w / ratio
  355. * w = h * ratio
  356. */
  357. switch ($mode) {
  358. case 'exact':
  359. $this->resizeExact($image, $newWidth, $newHeight);
  360. break;
  361. case 'fill':
  362. $this->resizeFill($image, $newWidth, $newHeight);
  363. break;
  364. case 'exactWidth':
  365. $this->resizeExactWidth($image, $newWidth);
  366. break;
  367. case 'exactHeight':
  368. $this->resizeExactHeight($image, $newHeight);
  369. break;
  370. case 'fit':
  371. $this->resizeFit($image, $newWidth, $newHeight);
  372. break;
  373. default:
  374. throw new \Exception(sprintf('Invalid resize mode "%s".', $mode));
  375. }
  376. return $this;
  377. }
  378. /**
  379. * Resize image to exact dimensions ignoring aspect ratio. Useful if you want to force exact width and height.
  380. *
  381. * @param Image $image
  382. * @param int $newWidth Width in pixels.
  383. * @param int $newHeight Height in pixels.
  384. *
  385. * @return self
  386. */
  387. public function resizeExact(&$image, $newWidth, $newHeight)
  388. {
  389. $this->_resize($image, $newWidth, $newHeight);
  390. return $this;
  391. }
  392. /**
  393. * Resize image to exact height. Width is auto calculated. Useful for creating row of images with the same height.
  394. *
  395. * @param Image $image
  396. * @param int $newHeight Height in pixels.
  397. *
  398. * @return self
  399. */
  400. public function resizeExactHeight(&$image, $newHeight)
  401. {
  402. $width = $image->getWidth();
  403. $height = $image->getHeight();
  404. $ratio = $width / $height;
  405. $resizeHeight = $newHeight;
  406. $resizeWidth = $newHeight * $ratio;
  407. $this->_resize($image, $resizeWidth, $resizeHeight);
  408. return $this;
  409. }
  410. /**
  411. * Resize image to exact width. Height is auto calculated. Useful for creating column of images with the same width.
  412. *
  413. * @param Image $image
  414. * @param int $newWidth Width in pixels.
  415. *
  416. * @return self
  417. */
  418. public function resizeExactWidth(&$image, $newWidth)
  419. {
  420. $width = $image->getWidth();
  421. $height = $image->getHeight();
  422. $ratio = $width / $height;
  423. $resizeWidth = $newWidth;
  424. $resizeHeight = round($newWidth / $ratio);
  425. $this->_resize($image, $resizeWidth, $resizeHeight);
  426. return $this;
  427. }
  428. /**
  429. * Resize image to fill all the space in the given dimension. Excess parts are cropped.
  430. *
  431. * @param Image $image
  432. * @param int $newWidth Width in pixels.
  433. * @param int $newHeight Height in pixels.
  434. *
  435. * @return self
  436. */
  437. public function resizeFill(&$image, $newWidth, $newHeight)
  438. {
  439. $width = $image->getWidth();
  440. $height = $image->getHeight();
  441. $ratio = $width / $height;
  442. // Base optimum size on new width
  443. $optimumWidth = $newWidth;
  444. $optimumHeight = round($newWidth / $ratio);
  445. if (($optimumWidth < $newWidth) or ($optimumHeight < $newHeight)) { // Oops, where trying to fill and there are blank areas
  446. // So base optimum size on height instead
  447. $optimumWidth = $newHeight * $ratio;
  448. $optimumHeight = $newHeight;
  449. }
  450. $this->_resize($image, $optimumWidth, $optimumHeight);
  451. $this->crop($image, $newWidth, $newHeight); // Trim excess parts
  452. return $this;
  453. }
  454. /**
  455. * Resize image to fit inside the given dimension. No part of the image is lost.
  456. *
  457. * @param Image $image
  458. * @param int $newWidth Width in pixels.
  459. * @param int $newHeight Height in pixels.
  460. *
  461. * @return self
  462. */
  463. public function resizeFit(&$image, $newWidth, $newHeight)
  464. {
  465. $width = $image->getWidth();
  466. $height = $image->getHeight();
  467. $ratio = $width / $height;
  468. // Try basing it on width first
  469. $resizeWidth = $newWidth;
  470. $resizeHeight = round($newWidth / $ratio);
  471. if (($resizeWidth > $newWidth) or ($resizeHeight > $newHeight)) { // Oops, either with or height does not fit
  472. // So base on height instead
  473. $resizeHeight = $newHeight;
  474. $resizeWidth = $newHeight * $ratio;
  475. }
  476. $this->_resize($image, $resizeWidth, $resizeHeight);
  477. return $this;
  478. }
  479. /**
  480. * Rotate an image counter-clockwise.
  481. *
  482. * @param Image $image
  483. * @param int $angle The angle in degrees.
  484. * @param Color|null $color The Color object containing the background color.
  485. *
  486. * @return EditorInterface An instance of image editor.
  487. */
  488. public function rotate(&$image, $angle, $color = null)
  489. {
  490. if ($image->isAnimated()) { // Ignore animated GIF for now
  491. return $this;
  492. }
  493. $color = ($color !== null) ? $color : new Color('#000000');
  494. list($r, $g, $b, $alpha) = $color->getRgba();
  495. $image->getCore()->rotateImage(new \ImagickPixel("rgba($r, $g, $b, $alpha)"), $angle * -1);
  496. return $this;
  497. }
  498. /**
  499. * Save the image to an image format.
  500. *
  501. * @param Image $image
  502. * @param string $file File path where to save the image.
  503. * @param null|string $type Type of image. Can be null, "GIF", "PNG", or "JPEG".
  504. * @param null|string $quality Quality of image. Applies to JPEG only. Accepts number 0 - 100 where 0 is lowest and 100 is the highest quality. Or null for default.
  505. * @param bool|false $interlace Set to true for progressive JPEG. Applies to JPEG only.
  506. * @param int $permission Default permission when creating non-existing target directory.
  507. *
  508. * @return Editor
  509. * @throws \Exception
  510. */
  511. public function save( $image, $file, $type = null, $quality = null, $interlace = false, $permission = 0755)
  512. {
  513. if (null === $type) {
  514. $type = $this->_getImageTypeFromFileName($file); // Null given, guess type from file extension
  515. if (ImageType::UNKNOWN === $type) {
  516. $type = $image->getType(); // 0 result, use original image type
  517. }
  518. }
  519. $targetDir = dirname($file); // $file's directory
  520. if (false === is_dir($targetDir)) { // Check if $file's directory exist
  521. // Create and set default perms to 0755
  522. if ( ! mkdir($targetDir, $permission, true)) {
  523. throw new \Exception(sprintf('Cannot create %s', $targetDir));
  524. }
  525. }
  526. switch (strtoupper($type)) {
  527. case ImageType::GIF :
  528. $image->getCore()->writeImages($file, true); // Support animated image. Eg. GIF
  529. break;
  530. case ImageType::PNG :
  531. // PNG is lossless and does not need compression. Although GD allow values 0-9 (0 = no compression), we leave it alone.
  532. $image->getCore()->setImageFormat($type);
  533. $image->getCore()->writeImage($file);
  534. break;
  535. default: // Defaults to jpeg
  536. $quality = ($quality === null) ? 75 : $quality; // Default to 75 (GDs default) if null.
  537. $quality = ($quality > 100) ? 100 : $quality;
  538. $quality = ($quality <= 0) ? 1 : $quality; // Note: If 0 change it to 1. The lowest quality in Imagick is 1 whereas in GD its 0.
  539. if ($interlace) {
  540. $image->getCore()->setImageInterlaceScheme(\Imagick::INTERLACE_JPEG);
  541. }
  542. $image->getCore()->setImageFormat($type);
  543. $image->getCore()->setImageCompression(\Imagick::COMPRESSION_JPEG);
  544. $image->getCore()->setImageCompressionQuality($quality);
  545. $image->getCore()->writeImage($file); // Single frame image. Eg. JPEG
  546. }
  547. return $this;
  548. }
  549. /**
  550. * Write text to image.
  551. *
  552. * @param Image $image
  553. * @param string $text The text to be written.
  554. * @param int $size The font size. Defaults to 12.
  555. * @param int $x The distance from the left edge of the image to the left of the text. Defaults to 0.
  556. * @param int $y The distance from the top edge of the image to the top of the text. Defaults to 12 (equal to font size) so that the text is placed within the image.
  557. * @param Color $color The Color object. Default text color is black.
  558. * @param string $font Full path to font file. If blank, will default to Liberation Sans font.
  559. * @param int $angle Angle of text from 0 - 359. Defaults to 0.
  560. *
  561. * @return EditorInterface
  562. * @throws \Exception
  563. */
  564. public function text(&$image, $text, $size = 12, $x = 0, $y = 0, $color = null, $font = '', $angle = 0)
  565. {
  566. if ($image->isAnimated()) { // Ignore animated GIF for now
  567. return $this;
  568. }
  569. $y += $size;
  570. $color = ($color !== null) ? $color : new Color('#000000');
  571. $font = ($font !== '') ? $font : Grafika::fontsDir() . DIRECTORY_SEPARATOR . 'LiberationSans-Regular.ttf';
  572. list($r, $g, $b, $alpha) = $color->getRgba();
  573. // Set up draw properties
  574. $draw = new \ImagickDraw();
  575. // Text color
  576. $draw->setFillColor(new \ImagickPixel("rgba($r, $g, $b, $alpha)"));
  577. // Font properties
  578. $draw->setFont($font);
  579. $draw->setFontSize($size);
  580. // Write text
  581. $image->getCore()->annotateImage(
  582. $draw,
  583. $x,
  584. $y,
  585. $angle,
  586. $text
  587. );
  588. return $this;
  589. }
  590. /**
  591. * Calculate entropy based on histogram.
  592. *
  593. * @param array $hist Histogram returned by Image->histogram
  594. *
  595. * @return float|int
  596. */
  597. private function _entropy($hist){
  598. $entropy = 0;
  599. $hist_size = array_sum($hist['r']) + array_sum($hist['g']) + array_sum($hist['b']);
  600. foreach($hist['r'] as $p){
  601. $p = $p / $hist_size;
  602. $entropy += $p * log($p, 2);
  603. }
  604. foreach($hist['g'] as $p){
  605. $p = $p / $hist_size;
  606. $entropy += $p * log($p, 2);
  607. }
  608. foreach($hist['b'] as $p){
  609. $p = $p / $hist_size;
  610. $entropy += $p * log($p, 2);
  611. }
  612. return $entropy * -1;
  613. }
  614. /**
  615. * Crop based on entropy.
  616. *
  617. * @param Image $oldImage
  618. * @param $cropW
  619. * @param $cropH
  620. *
  621. * @return array
  622. */
  623. private function _smartCrop($oldImage, $cropW, $cropH){
  624. $image = clone $oldImage;
  625. $this->resizeFit($image, 30, 30);
  626. $origW = $oldImage->getWidth();
  627. $origH = $oldImage->getHeight();
  628. $resizeW = $image->getWidth();
  629. $resizeH = $image->getHeight();
  630. $smallCropW = round(($resizeW / $origW) * $cropW);
  631. $smallCropH = round(($resizeH / $origH) * $cropH);
  632. $step = 1;
  633. for($y = 0; $y < $resizeH-$smallCropH; $y+=$step){
  634. for($x = 0; $x < $resizeW-$smallCropW; $x+=$step){
  635. $hist[$x.'-'.$y] = $this->_entropy($image->histogram(array(array($x, $y), array($smallCropW, $smallCropH))));
  636. }
  637. if($resizeW-$smallCropW <= 0){
  638. $hist['0-'.$y] = $this->_entropy($image->histogram(array(array(0, 0), array($smallCropW, $smallCropH))));
  639. }
  640. }
  641. if($resizeH-$smallCropH <= 0){
  642. $hist['0-0'] = $this->_entropy($image->histogram(array(array(0, 0), array($smallCropW, $smallCropH))));
  643. }
  644. asort($hist);
  645. end($hist);
  646. $pos = key($hist); // last key
  647. list($x, $y) = explode('-', $pos);
  648. $x = round($x*($origW / $resizeW));
  649. $y = round($y*($origH / $resizeH));
  650. return array($x,$y);
  651. }
  652. /**
  653. * Resize helper function.
  654. *
  655. * @param Image $image
  656. * @param int $newWidth
  657. * @param int $newHeight
  658. *
  659. * @return self
  660. * @throws \Exception
  661. */
  662. private function _resize(&$image, $newWidth, $newHeight)
  663. {
  664. if ('GIF' == $image->getType()) { // Animated image. Eg. GIF
  665. $imagick = $image->getCore()->coalesceImages();
  666. foreach ($imagick as $frame) {
  667. $frame->resizeImage($newWidth, $newHeight, \Imagick::FILTER_BOX, 1, false);
  668. $frame->setImagePage($newWidth, $newHeight, 0, 0);
  669. }
  670. // Assign new image with frames
  671. $image = new Image($imagick->deconstructImages(), $image->getImageFile(), $newWidth, $newHeight,
  672. $image->getType());
  673. } else { // Single frame image. Eg. JPEG, PNG
  674. $image->getCore()->resizeImage($newWidth, $newHeight, \Imagick::FILTER_LANCZOS, 1, false);
  675. // Assign new image
  676. $image = new Image($image->getCore(), $image->getImageFile(), $newWidth, $newHeight,
  677. $image->getType());
  678. }
  679. }
  680. /**
  681. * Get image type base on file extension.
  682. *
  683. * @param int $imageFile File path to image.
  684. *
  685. * @return ImageType string Type of image.
  686. */
  687. private function _getImageTypeFromFileName($imageFile)
  688. {
  689. $ext = strtolower((string)pathinfo($imageFile, PATHINFO_EXTENSION));
  690. if ('jpg' == $ext or 'jpeg' == $ext) {
  691. return ImageType::JPEG;
  692. } else if ('gif' == $ext) {
  693. return ImageType::GIF;
  694. } else if ('png' == $ext) {
  695. return ImageType::PNG;
  696. } else {
  697. return ImageType::UNKNOWN;
  698. }
  699. }
  700. }