Editor.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. <?php
  2. namespace Grafika\Gd;
  3. use Grafika\DrawingObjectInterface;
  4. use Grafika\EditorInterface;
  5. use Grafika\FilterInterface;
  6. use Grafika\Gd\Helper\GifHelper;
  7. use Grafika\Gd\ImageHash\DifferenceHash;
  8. use Grafika\Grafika;
  9. use Grafika\ImageInterface;
  10. use Grafika\ImageType;
  11. use Grafika\Color;
  12. use Grafika\Position;
  13. /**
  14. * GD Editor class. Uses the PHP GD library.
  15. * @package Grafika\Gd
  16. */
  17. final class Editor implements EditorInterface
  18. {
  19. /**
  20. * Apply a filter to the image. See Filters section for a list of available filters.
  21. *
  22. * @param Image $image
  23. * @param FilterInterface $filter
  24. *
  25. * @return Editor
  26. */
  27. public function apply( &$image, $filter)
  28. {
  29. if ($image->isAnimated()) { // Ignore animated GIF for now
  30. return $this;
  31. }
  32. $image = $filter->apply($image);
  33. return $this;
  34. }
  35. /**
  36. * Blend two images together with the first image as the base and the second image on top. Supports several blend modes.
  37. *
  38. * @param Image $image1 The base image.
  39. * @param Image $image2 The image placed on top of the base image.
  40. * @param string $type The blend mode. Can be: normal, multiply, overlay or screen.
  41. * @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.
  42. * @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.
  43. * @param int $offsetX Number of pixels to add to the X position of $image2.
  44. * @param int $offsetY Number of pixels to add to the Y position of $image2.
  45. *
  46. * @return Editor
  47. * @throws \Exception When added image is outside of canvas or invalid blend type
  48. */
  49. public function blend(&$image1, $image2, $type='normal', $opacity = 1.0, $position = 'top-left', $offsetX = 0, $offsetY = 0 ){
  50. // Turn into position object
  51. $position = new Position($position, $offsetX, $offsetY);
  52. // Position is for $image2. $image1 is canvas.
  53. list($offsetX, $offsetY) = $position->getXY($image1->getWidth(), $image1->getHeight(), $image2->getWidth(), $image2->getHeight());
  54. // Check if it overlaps
  55. if( ($offsetX >= $image1->getWidth() ) or
  56. ($offsetX + $image2->getWidth() <= 0) or
  57. ($offsetY >= $image1->getHeight() ) or
  58. ($offsetY + $image2->getHeight() <= 0)){
  59. throw new \Exception('Invalid blending. Image 2 is outside the canvas.');
  60. }
  61. // Loop start X
  62. $loopStartX = 0;
  63. $canvasStartX = $offsetX;
  64. if($canvasStartX < 0){
  65. $diff = 0 - $canvasStartX;
  66. $loopStartX += $diff;
  67. }
  68. // Loop end X
  69. $loopEndX = $image2->getWidth();
  70. $canvasEndX = $offsetX + $image2->getWidth();
  71. if($canvasEndX > $image1->getWidth()){
  72. $diff = $canvasEndX - $image1->getWidth();
  73. $loopEndX -= $diff;
  74. }
  75. // Loop start Y
  76. $loopStartY = 0;
  77. $canvasStartY = $offsetY;
  78. if($canvasStartY < 0){
  79. $diff = 0 - $canvasStartY;
  80. $loopStartY += $diff;
  81. }
  82. // Loop end Y
  83. $loopEndY = $image2->getHeight();
  84. $canvasEndY = $offsetY + $image2->getHeight();
  85. if($canvasEndY > $image1->getHeight()){
  86. $diff = $canvasEndY - ($image1->getHeight());
  87. $loopEndY -= $diff;
  88. }
  89. $w = $image1->getWidth();
  90. $h = $image1->getHeight();
  91. $gd1 = $image1->getCore();
  92. $gd2 = $image2->getCore();
  93. $canvas = imagecreatetruecolor( $w, $h );
  94. imagecopy( $canvas, $gd1, 0, 0, 0, 0, $w, $h );
  95. $type = strtolower( $type );
  96. if($type==='normal') {
  97. if ( $opacity !== 1 ) {
  98. $this->opacity($image2, $opacity);
  99. }
  100. imagecopy( $canvas, $gd2, $loopStartX + $offsetX, $loopStartY + $offsetY, 0, 0, $image2->getWidth(), $image2->getHeight());
  101. } else if($type==='multiply'){
  102. $this->_blendMultiply( $canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity );
  103. } else if($type==='overlay'){
  104. $this->_blendOverlay( $canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity );
  105. } else if($type==='screen'){
  106. $this->_blendScreen( $canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity );
  107. } else {
  108. throw new \Exception(sprintf('Invalid blend type "%s".', $type));
  109. }
  110. imagedestroy( $gd1 ); // Free resource
  111. $image1 = new Image(
  112. $canvas,
  113. $image1->getImageFile(),
  114. $w,
  115. $h,
  116. $image1->getType()
  117. );
  118. return $this;
  119. }
  120. /**
  121. * 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.
  122. *
  123. * @param ImageInterface|string $image1
  124. * @param ImageInterface|string $image2
  125. *
  126. * @return int Hamming distance. Note: This breaks the chain if you are doing fluent api calls as it does not return an Editor.
  127. * @throws \Exception
  128. */
  129. public function compare($image1, $image2)
  130. {
  131. if (is_string($image1)) { // If string passed, turn it into a Image object
  132. $image1 = Image::createFromFile($image1);
  133. $this->flatten( $image1 );
  134. }
  135. if (is_string($image2)) { // If string passed, turn it into a Image object
  136. $image2 = Image::createFromFile($image2);
  137. $this->flatten( $image2 );
  138. }
  139. $hash = new DifferenceHash();
  140. $bin1 = $hash->hash($image1, $this);
  141. $bin2 = $hash->hash($image2, $this);
  142. $str1 = str_split($bin1);
  143. $str2 = str_split($bin2);
  144. $distance = 0;
  145. foreach ($str1 as $i => $char) {
  146. if ($char !== $str2[$i]) {
  147. $distance++;
  148. }
  149. }
  150. return $distance;
  151. }
  152. /**
  153. * Crop the image to the given dimension and position.
  154. *
  155. * @param Image $image
  156. * @param int $cropWidth Crop width in pixels.
  157. * @param int $cropHeight Crop Height in pixels.
  158. * @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.
  159. * @param int $offsetX Number of pixels to add to the X position of the crop.
  160. * @param int $offsetY Number of pixels to add to the Y position of the crop.
  161. *
  162. * @return Editor
  163. * @throws \Exception
  164. */
  165. public function crop( &$image, $cropWidth, $cropHeight, $position = 'center', $offsetX = 0, $offsetY = 0)
  166. {
  167. if ($image->isAnimated()) { // Ignore animated GIF for now
  168. return $this;
  169. }
  170. if ( 'smart' === $position ) { // Smart crop
  171. list( $x, $y ) = $this->_smartCrop( $image, $cropWidth, $cropHeight );
  172. } else {
  173. // Turn into an instance of Position
  174. $position = new Position( $position, $offsetX, $offsetY );
  175. // Crop position as x,y coordinates
  176. list( $x, $y ) = $position->getXY( $image->getWidth(), $image->getHeight(), $cropWidth, $cropHeight );
  177. }
  178. // Create blank image
  179. $newImageResource = imagecreatetruecolor($cropWidth, $cropHeight);
  180. // Now crop
  181. imagecopyresampled(
  182. $newImageResource, // Target image
  183. $image->getCore(), // Source image
  184. 0, // Target x
  185. 0, // Target y
  186. $x, // Src x
  187. $y, // Src y
  188. $cropWidth, // Target width
  189. $cropHeight, // Target height
  190. $cropWidth, // Src width
  191. $cropHeight // Src height
  192. );
  193. // Free memory of old resource
  194. imagedestroy($image->getCore());
  195. // Cropped image instance
  196. $image = new Image(
  197. $newImageResource,
  198. $image->getImageFile(),
  199. $cropWidth,
  200. $cropHeight,
  201. $image->getType()
  202. );
  203. return $this;
  204. }
  205. /**
  206. * Draw a DrawingObject on the image. See Drawing Objects section.
  207. *
  208. * @param Image $image
  209. * @param DrawingObjectInterface $drawingObject
  210. *
  211. * @return $this
  212. */
  213. public function draw( &$image, $drawingObject)
  214. {
  215. if ($image->isAnimated()) { // Ignore animated GIF for now
  216. return $this;
  217. }
  218. $image = $drawingObject->draw($image);
  219. return $this;
  220. }
  221. /**
  222. * 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.
  223. *
  224. * @param string|ImageInterface $image1 Can be an instance of Image or string containing the file system path to image.
  225. * @param string|ImageInterface $image2 Can be an instance of Image or string containing the file system path to image.
  226. *
  227. * @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.
  228. * @throws \Exception
  229. */
  230. public function equal($image1, $image2)
  231. {
  232. if (is_string($image1)) { // If string passed, turn it into a Image object
  233. $image1 = Image::createFromFile($image1);
  234. $this->flatten( $image1 );
  235. }
  236. if (is_string($image2)) { // If string passed, turn it into a Image object
  237. $image2 = Image::createFromFile($image2);
  238. $this->flatten( $image2 );
  239. }
  240. // Check if image dimensions are equal
  241. if ($image1->getWidth() !== $image2->getWidth() or $image1->getHeight() !== $image2->getHeight()) {
  242. return false;
  243. } else {
  244. // Loop using image1
  245. for ($y = 0; $y < $image1->getHeight(); $y++) {
  246. for ($x = 0; $x < $image1->getWidth(); $x++) {
  247. // Get image1 pixel
  248. $rgb1 = imagecolorat($image1->getCore(), $x, $y);
  249. $r1 = ($rgb1 >> 16) & 0xFF;
  250. $g1 = ($rgb1 >> 8) & 0xFF;
  251. $b1 = $rgb1 & 0xFF;
  252. // Get image2 pixel
  253. $rgb2 = imagecolorat($image2->getCore(), $x, $y);
  254. $r2 = ($rgb2 >> 16) & 0xFF;
  255. $g2 = ($rgb2 >> 8) & 0xFF;
  256. $b2 = $rgb2 & 0xFF;
  257. // Compare pixel value
  258. if (
  259. $r1 !== $r2 or
  260. $g1 !== $g2 or
  261. $b1 !== $b2
  262. ) {
  263. return false;
  264. }
  265. }
  266. }
  267. }
  268. return true;
  269. }
  270. /**
  271. * Fill entire image with color.
  272. *
  273. * @param Image $image
  274. * @param Color $color Color object
  275. * @param int $x X-coordinate of start point
  276. * @param int $y Y-coordinate of start point
  277. *
  278. * @return Editor
  279. */
  280. public function fill( &$image, $color, $x = 0, $y = 0)
  281. {
  282. if ($image->isAnimated()) { // Ignore animated GIF for now
  283. return $this;
  284. }
  285. list($r, $g, $b, $alpha) = $color->getRgba();
  286. $colorResource = imagecolorallocatealpha($image->getCore(), $r, $g, $b,
  287. $this->gdAlpha($alpha));
  288. imagefill($image->getCore(), $x, $y, $colorResource);
  289. return $this;
  290. }
  291. /**
  292. * Flatten if animated GIF. Do nothing otherwise.
  293. *
  294. * @param Image $image
  295. *
  296. * @return Editor
  297. */
  298. public function flatten(&$image){
  299. if($image->isAnimated()) {
  300. $old = $image->getCore();
  301. $gift = new GifHelper();
  302. $hex = $gift->encode($image->getBlocks());
  303. $gd = imagecreatefromstring(pack('H*', $hex)); // Recreate resource from blocks
  304. imagedestroy( $old ); // Free resource
  305. $image = new Image(
  306. $gd,
  307. $image->getImageFile(),
  308. $image->getWidth(),
  309. $image->getHeight(),
  310. $image->getType(),
  311. '', // blocks
  312. false // animated
  313. );
  314. }
  315. return $this;
  316. }
  317. /**
  318. * Flip or mirrors the image.
  319. *
  320. * @param Image $image
  321. * @param string $mode The type of flip: 'h' for horizontal flip or 'v' for vertical.
  322. *
  323. * @return Editor
  324. * @throws \Exception
  325. */
  326. public function flip(&$image, $mode){
  327. $image = $this->_flip($image, $mode);
  328. return $this;
  329. }
  330. /**
  331. * Free the image clearing resources associated with it.
  332. *
  333. * @param Image $image
  334. *
  335. * @return Editor
  336. */
  337. public function free( &$image )
  338. {
  339. imagedestroy($image->getCore());
  340. return $this;
  341. }
  342. /**
  343. * Convert alpha value of 0 - 1 to GD compatible alpha value of 0 - 127 where 0 is opaque and 127 is transparent
  344. *
  345. * @param float $alpha Alpha value of 0 - 1. Example: 0, 0.60, 0.9, 1
  346. *
  347. * @return int
  348. */
  349. public static function gdAlpha($alpha)
  350. {
  351. $scale = round(127 * $alpha);
  352. return $invert = 127 - $scale;
  353. }
  354. /**
  355. * Checks if the editor is available on the current PHP install.
  356. *
  357. * @return bool True if available false if not.
  358. */
  359. public function isAvailable()
  360. {
  361. if (false === extension_loaded('gd') || false === function_exists('gd_info')) {
  362. return false;
  363. }
  364. // On some setups GD library does not provide imagerotate()
  365. if ( ! function_exists('imagerotate')) {
  366. return false;
  367. }
  368. return true;
  369. }
  370. /**
  371. * Sets the image to the specified opacity level where 1.0 is fully opaque and 0.0 is fully transparent.
  372. * Warning: This function loops thru each pixel manually which can be slow. Use sparingly.
  373. *
  374. * @param Image $image
  375. * @param float $opacity
  376. *
  377. * @return Editor
  378. * @throws \Exception
  379. */
  380. public function opacity( &$image, $opacity )
  381. {
  382. if ($image->isAnimated()) { // Ignore animated GIF for now
  383. return $this;
  384. }
  385. // Bounds checks
  386. $opacity = ($opacity > 1) ? 1 : $opacity;
  387. $opacity = ($opacity < 0) ? 0 : $opacity;
  388. for ($y = 0; $y < $image->getHeight(); $y++) {
  389. for ($x = 0; $x < $image->getWidth(); $x++) {
  390. $rgb = imagecolorat($image->getCore(), $x, $y);
  391. $alpha = ($rgb >> 24) & 0x7F; // 127 in hex. These are binary operations.
  392. $r = ($rgb >> 16) & 0xFF;
  393. $g = ($rgb >> 8) & 0xFF;
  394. $b = $rgb & 0xFF;
  395. // Reverse alpha values from 127-0 (transparent to opaque) to 0-127 for easy math
  396. // Previously: 0 = opaque, 127 = transparent.
  397. // Now: 0 = transparent, 127 = opaque
  398. $reverse = 127 - $alpha;
  399. $reverse = round($reverse * $opacity);
  400. if ($alpha < 127) { // Process non transparent pixels only
  401. imagesetpixel($image->getCore(), $x, $y,
  402. imagecolorallocatealpha($image->getCore(), $r, $g, $b, 127 - $reverse));
  403. }
  404. }
  405. }
  406. return $this;
  407. }
  408. /**
  409. * Open an image file and assign Image to first parameter.
  410. *
  411. * @param Image $image
  412. * @param string $imageFile
  413. *
  414. * @return Editor
  415. */
  416. public function open(&$image, $imageFile){
  417. $image = Image::createFromFile( $imageFile );
  418. return $this;
  419. }
  420. /**
  421. * Wrapper function for the resizeXXX family of functions. Resize image given width, height and mode.
  422. *
  423. * @param Image $image
  424. * @param int $newWidth Width in pixels.
  425. * @param int $newHeight Height in pixels.
  426. * @param string $mode Resize mode. Possible values: "exact", "exactHeight", "exactWidth", "fill", "fit".
  427. *
  428. * @return Editor
  429. * @throws \Exception
  430. */
  431. public function resize(&$image, $newWidth, $newHeight, $mode = 'fit')
  432. {
  433. /*
  434. * Resize formula:
  435. * ratio = w / h
  436. * h = w / ratio
  437. * w = h * ratio
  438. */
  439. switch ($mode) {
  440. case 'exact':
  441. $this->resizeExact($image, $newWidth, $newHeight);
  442. break;
  443. case 'fill':
  444. $this->resizeFill($image, $newWidth, $newHeight);
  445. break;
  446. case 'exactWidth':
  447. $this->resizeExactWidth($image, $newWidth);
  448. break;
  449. case 'exactHeight':
  450. $this->resizeExactHeight($image, $newHeight);
  451. break;
  452. case 'fit':
  453. $this->resizeFit($image, $newWidth, $newHeight);
  454. break;
  455. default:
  456. throw new \Exception(sprintf('Invalid resize mode "%s".', $mode));
  457. }
  458. return $this;
  459. }
  460. /**
  461. * Resize image to exact dimensions ignoring aspect ratio. Useful if you want to force exact width and height.
  462. *
  463. * @param Image $image
  464. * @param int $newWidth Width in pixels.
  465. * @param int $newHeight Height in pixels.
  466. *
  467. * @return Editor
  468. */
  469. public function resizeExact(&$image, $newWidth, $newHeight)
  470. {
  471. $this->_resize($image, $newWidth, $newHeight);
  472. return $this;
  473. }
  474. /**
  475. * Resize image to exact height. Width is auto calculated. Useful for creating row of images with the same height.
  476. *
  477. * @param Image $image
  478. * @param int $newHeight Height in pixels.
  479. *
  480. * @return Editor
  481. */
  482. public function resizeExactHeight(&$image, $newHeight)
  483. {
  484. $width = $image->getWidth();
  485. $height = $image->getHeight();
  486. $ratio = $width / $height;
  487. $resizeHeight = $newHeight;
  488. $resizeWidth = $newHeight * $ratio;
  489. $this->_resize($image, $resizeWidth, $resizeHeight);
  490. return $this;
  491. }
  492. /**
  493. * Resize image to exact width. Height is auto calculated. Useful for creating column of images with the same width.
  494. *
  495. * @param Image $image
  496. * @param int $newWidth Width in pixels.
  497. *
  498. * @return Editor
  499. */
  500. public function resizeExactWidth(&$image, $newWidth)
  501. {
  502. $width = $image->getWidth();
  503. $height = $image->getHeight();
  504. $ratio = $width / $height;
  505. $resizeWidth = $newWidth;
  506. $resizeHeight = round($newWidth / $ratio);
  507. $this->_resize($image, $resizeWidth, $resizeHeight);
  508. return $this;
  509. }
  510. /**
  511. * Resize image to fill all the space in the given dimension. Excess parts are cropped.
  512. *
  513. * @param Image $image
  514. * @param int $newWidth Width in pixels.
  515. * @param int $newHeight Height in pixels.
  516. *
  517. * @return Editor
  518. */
  519. public function resizeFill(&$image, $newWidth, $newHeight)
  520. {
  521. $width = $image->getWidth();
  522. $height = $image->getHeight();
  523. $ratio = $width / $height;
  524. // Base optimum size on new width
  525. $optimumWidth = $newWidth;
  526. $optimumHeight = round($newWidth / $ratio);
  527. if (($optimumWidth < $newWidth) or ($optimumHeight < $newHeight)) { // Oops, where trying to fill and there are blank areas
  528. // So base optimum size on height instead
  529. $optimumWidth = $newHeight * $ratio;
  530. $optimumHeight = $newHeight;
  531. }
  532. $this->_resize($image, $optimumWidth, $optimumHeight);
  533. $this->crop($image, $newWidth, $newHeight); // Trim excess parts
  534. return $this;
  535. }
  536. /**
  537. * Resize image to fit inside the given dimension. No part of the image is lost.
  538. *
  539. * @param Image $image
  540. * @param int $newWidth Width in pixels.
  541. * @param int $newHeight Height in pixels.
  542. *
  543. * @return Editor
  544. */
  545. public function resizeFit(&$image, $newWidth, $newHeight)
  546. {
  547. $width = $image->getWidth();
  548. $height = $image->getHeight();
  549. $ratio = $width / $height;
  550. // Try basing it on width first
  551. $resizeWidth = $newWidth;
  552. $resizeHeight = round($newWidth / $ratio);
  553. if (($resizeWidth > $newWidth) or ($resizeHeight > $newHeight)) { // Oops, either with or height does not fit
  554. // So base on height instead
  555. $resizeHeight = $newHeight;
  556. $resizeWidth = $newHeight * $ratio;
  557. }
  558. $this->_resize($image, $resizeWidth, $resizeHeight);
  559. return $this;
  560. }
  561. /**
  562. * Rotate an image counter-clockwise.
  563. *
  564. * @param Image $image
  565. * @param int $angle The angle in degrees.
  566. * @param Color|null $color The Color object containing the background color.
  567. *
  568. * @return EditorInterface An instance of image editor.
  569. * @throws \Exception
  570. */
  571. public function rotate(&$image, $angle, $color = null)
  572. {
  573. if ($image->isAnimated()) { // Ignore animated GIF for now
  574. return $this;
  575. }
  576. $color = ($color !== null) ? $color : new Color('#000000');
  577. list($r, $g, $b, $alpha) = $color->getRgba();
  578. $old = $image->getCore();
  579. $new = imagerotate($old, $angle, imagecolorallocatealpha($old, $r, $g, $b, $alpha));
  580. if(false === $new){
  581. throw new \Exception('Error rotating image.');
  582. }
  583. imagedestroy( $old ); // Free resource
  584. $image = new Image( $new, $image->getImageFile(), $image->getWidth(), $image->getHeight(), $image->getType() );
  585. return $this;
  586. }
  587. /**
  588. * Save the image to an image format.
  589. *
  590. * @param Image $image
  591. * @param string $file File path where to save the image.
  592. * @param null|string $type Type of image. Can be null, "GIF", "PNG", or "JPEG".
  593. * @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.
  594. * @param bool|false $interlace Set to true for progressive JPEG. Applies to JPEG only.
  595. * @param int $permission Default permission when creating non-existing target directory.
  596. *
  597. * @return Editor
  598. * @throws \Exception
  599. */
  600. public function save($image, $file, $type = null, $quality = null, $interlace = false, $permission = 0755)
  601. {
  602. if (null === $type) {
  603. $type = $this->_getImageTypeFromFileName($file); // Null given, guess type from file extension
  604. if (ImageType::UNKNOWN === $type) {
  605. $type = $image->getType(); // 0 result, use original image type
  606. }
  607. }
  608. $targetDir = dirname($file); // $file's directory
  609. if (false === is_dir($targetDir)) { // Check if $file's directory exist
  610. // Create and set default perms to 0755
  611. if ( ! mkdir($targetDir, $permission, true)) {
  612. throw new \Exception(sprintf('Cannot create %s', $targetDir));
  613. }
  614. }
  615. switch (strtoupper($type)) {
  616. case ImageType::GIF :
  617. if($image->isAnimated()){
  618. $blocks = $image->getBlocks();
  619. $gift = new GifHelper();
  620. $hex = $gift->encode($blocks);
  621. file_put_contents($file, pack('H*', $hex));
  622. } else {
  623. imagegif($image->getCore(), $file);
  624. }
  625. break;
  626. case ImageType::PNG :
  627. // PNG is lossless and does not need compression. Although GD allow values 0-9 (0 = no compression), we leave it alone.
  628. imagepng($image->getCore(), $file);
  629. break;
  630. default: // Defaults to jpeg
  631. $quality = ($quality === null) ? 75 : $quality; // Default to 75 (GDs default) if null.
  632. $quality = ($quality > 100) ? 100 : $quality;
  633. $quality = ($quality < 0) ? 0 : $quality;
  634. imageinterlace($image->getCore(), $interlace);
  635. imagejpeg($image->getCore(), $file, $quality);
  636. }
  637. return $this;
  638. }
  639. /**
  640. * Write text to image.
  641. *
  642. * @param Image $image
  643. * @param string $text The text to be written.
  644. * @param int $size The font size. Defaults to 12.
  645. * @param int $x The distance from the left edge of the image to the left of the text. Defaults to 0.
  646. * @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.
  647. * @param Color $color The Color object. Default text color is black.
  648. * @param string $font Full path to font file. If blank, will default to Liberation Sans font.
  649. * @param int $angle Angle of text from 0 - 359. Defaults to 0.
  650. *
  651. * @return EditorInterface
  652. * @throws \Exception
  653. */
  654. public function text(&$image, $text, $size = 12, $x = 0, $y = 0, $color = null, $font = '', $angle = 0)
  655. {
  656. if ($image->isAnimated()) { // Ignore animated GIF for now
  657. return $this;
  658. }
  659. $y += $size;
  660. $color = ($color !== null) ? $color : new Color('#000000');
  661. $font = ($font !== '') ? $font : Grafika::fontsDir() . DIRECTORY_SEPARATOR . 'LiberationSans-Regular.ttf';
  662. list($r, $g, $b, $alpha) = $color->getRgba();
  663. $colorResource = imagecolorallocatealpha(
  664. $image->getCore(),
  665. $r, $g, $b,
  666. $this->gdAlpha($alpha)
  667. );
  668. imagettftext(
  669. $image->getCore(),
  670. $size,
  671. $angle,
  672. $x,
  673. $y,
  674. $colorResource,
  675. $font,
  676. $text
  677. );
  678. return $this;
  679. }
  680. /**
  681. * @param $canvas
  682. * @param $gd1
  683. * @param $gd2
  684. * @param $loopStartY
  685. * @param $loopEndY
  686. * @param $loopStartX
  687. * @param $loopEndX
  688. * @param $offsetX
  689. * @param $offsetY
  690. *
  691. * @param $opacity
  692. *
  693. * @return $this
  694. */
  695. private function _blendMultiply($canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity){
  696. for ( $y = $loopStartY; $y < $loopEndY; $y++ ) {
  697. for ( $x = $loopStartX; $x < $loopEndX; $x++ ) {
  698. $canvasX = $x + $offsetX;
  699. $canvasY = $y + $offsetY;
  700. $argb1 = imagecolorat( $gd1, $canvasX, $canvasY );
  701. $r1 = ( $argb1 >> 16 ) & 0xFF;
  702. $g1 = ( $argb1 >> 8 ) & 0xFF;
  703. $b1 = $argb1 & 0xFF;
  704. $argb2 = imagecolorat( $gd2, $x, $y );
  705. $a2 = ($argb2 >> 24) & 0x7F; // 127 in hex. These are binary operations.
  706. $r2 = ( $argb2 >> 16 ) & 0xFF;
  707. $g2 = ( $argb2 >> 8 ) & 0xFF;
  708. $b2 = $argb2 & 0xFF;
  709. $r3 = round($r1 * $r2 / 255);
  710. $g3 = round($g1 * $g2 / 255);
  711. $b3 = round($b1 * $b2 / 255);
  712. $reverse = 127 - $a2;
  713. $reverse = round($reverse * $opacity);
  714. $argb3 = imagecolorallocatealpha( $canvas, $r3, $g3, $b3, 127 - $reverse );
  715. imagesetpixel( $canvas, $canvasX, $canvasY, $argb3 );
  716. }
  717. }
  718. return $canvas;
  719. }
  720. /**
  721. * @param $canvas
  722. * @param $gd1
  723. * @param $gd2
  724. * @param $loopStartY
  725. * @param $loopEndY
  726. * @param $loopStartX
  727. * @param $loopEndX
  728. * @param $offsetX
  729. * @param $offsetY
  730. *
  731. * @param $opacity
  732. *
  733. * @return $this
  734. */
  735. private function _blendOverlay($canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity){
  736. for ( $y = $loopStartY; $y < $loopEndY; $y++ ) {
  737. for ( $x = $loopStartX; $x < $loopEndX; $x++ ) {
  738. $canvasX = $x + $offsetX;
  739. $canvasY = $y + $offsetY;
  740. $argb1 = imagecolorat( $gd1, $canvasX, $canvasY );
  741. $r1 = ( $argb1 >> 16 ) & 0xFF;
  742. $g1 = ( $argb1 >> 8 ) & 0xFF;
  743. $b1 = $argb1 & 0xFF;
  744. $argb2 = imagecolorat( $gd2, $x, $y );
  745. $a2 = ($argb2 >> 24) & 0x7F; // 127 in hex. These are binary operations.
  746. $r2 = ( $argb2 >> 16 ) & 0xFF;
  747. $g2 = ( $argb2 >> 8 ) & 0xFF;
  748. $b2 = $argb2 & 0xFF;
  749. $r1 /= 255;
  750. $r2 /= 255;
  751. if ($r1 < 0.5) {
  752. $r3 = 2 * ($r1 * $r2);
  753. } else {
  754. $r3 = (1 - (2 *(1-$r1)) * (1-$r2));
  755. }
  756. $g1 /= 255;
  757. $g2 /= 255;
  758. if ($g1 < 0.5) {
  759. $g3 = 2 * ($g1 * $g2);
  760. } else {
  761. $g3 = (1 - (2 *(1-$g1)) * (1-$g2));
  762. }
  763. $b1 /= 255;
  764. $b2 /= 255;
  765. if ($b1 < 0.5) {
  766. $b3 = 2 * ($b1 * $b2);
  767. } else {
  768. $b3 = (1 - (2 *(1-$b1)) * (1-$b2));
  769. }
  770. $reverse = 127 - $a2;
  771. $reverse = round($reverse * $opacity);
  772. $argb3 = imagecolorallocatealpha( $canvas, $r3*255, $g3*255, $b3*255, 127 - $reverse );
  773. imagesetpixel( $canvas, $canvasX, $canvasY, $argb3 );
  774. }
  775. }
  776. return $canvas;
  777. }
  778. /**
  779. * Calculate entropy based on histogram.
  780. *
  781. * @param $hist
  782. *
  783. * @return float|int
  784. */
  785. private function _entropy($hist){
  786. $entropy = 0;
  787. $hist_size = array_sum($hist['r']) + array_sum($hist['g']) + array_sum($hist['b']);
  788. foreach($hist['r'] as $p){
  789. $p = $p / $hist_size;
  790. $entropy += $p * log($p, 2);
  791. }
  792. foreach($hist['g'] as $p){
  793. $p = $p / $hist_size;
  794. $entropy += $p * log($p, 2);
  795. }
  796. foreach($hist['b'] as $p){
  797. $p = $p / $hist_size;
  798. $entropy += $p * log($p, 2);
  799. }
  800. return $entropy * -1;
  801. }
  802. /**
  803. * @param $canvas
  804. * @param $gd1
  805. * @param $gd2
  806. * @param $loopStartY
  807. * @param $loopEndY
  808. * @param $loopStartX
  809. * @param $loopEndX
  810. * @param $offsetX
  811. * @param $offsetY
  812. *
  813. * @param $opacity
  814. *
  815. * @return $this
  816. */
  817. private function _blendScreen($canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity){
  818. for ( $y = $loopStartY; $y < $loopEndY; $y++ ) {
  819. for ( $x = $loopStartX; $x < $loopEndX; $x++ ) {
  820. $canvasX = $x + $offsetX;
  821. $canvasY = $y + $offsetY;
  822. $argb1 = imagecolorat( $gd1, $canvasX, $canvasY );
  823. $r1 = ( $argb1 >> 16 ) & 0xFF;
  824. $g1 = ( $argb1 >> 8 ) & 0xFF;
  825. $b1 = $argb1 & 0xFF;
  826. $argb2 = imagecolorat( $gd2, $x, $y );
  827. $a2 = ($argb2 >> 24) & 0x7F; // 127 in hex. These are binary operations.
  828. $r2 = ( $argb2 >> 16 ) & 0xFF;
  829. $g2 = ( $argb2 >> 8 ) & 0xFF;
  830. $b2 = $argb2 & 0xFF;
  831. $r3 = 255 - ( ( 255 - $r1 ) * ( 255 - $r2 ) ) / 255;
  832. $g3 = 255 - ( ( 255 - $g1 ) * ( 255 - $g2 ) ) / 255;
  833. $b3 = 255 - ( ( 255 - $b1 ) * ( 255 - $b2 ) ) / 255;
  834. $reverse = 127 - $a2;
  835. $reverse = round($reverse * $opacity);
  836. $argb3 = imagecolorallocatealpha( $canvas, $r3, $g3, $b3, 127 - $reverse );
  837. imagesetpixel( $canvas, $canvasX, $canvasY, $argb3 );
  838. }
  839. }
  840. return $canvas;
  841. }
  842. /**
  843. * Flips image.
  844. * @param Image $image
  845. * @param $mode
  846. *
  847. * @return Image
  848. * @throws \Exception
  849. */
  850. private function _flip($image, $mode)
  851. {
  852. $old = $image->getCore();
  853. $w = $image->getWidth();
  854. $h = $image->getHeight();
  855. if ($mode === 'h') {
  856. $new = imagecreatetruecolor($w, $h);
  857. for ($x = 0; $x < $w; $x++) {
  858. imagecopy($new, $old, $w - $x - 1, 0, $x, 0, 1, $h);
  859. }
  860. imagedestroy($old); // Free resource
  861. return new Image(
  862. $new,
  863. $image->getImageFile(),
  864. $w,
  865. $h,
  866. $image->getType(),
  867. $image->getBlocks(),
  868. $image->isAnimated()
  869. );
  870. } else if ($mode === 'v') {
  871. $new = imagecreatetruecolor($w, $h);
  872. for ($y = 0; $y < $h; $y++) {
  873. imagecopy($new, $old, 0, $h - $y - 1, 0, $y, $w, 1);
  874. }
  875. imagedestroy($old); // Free resource
  876. return new Image(
  877. $new,
  878. $image->getImageFile(),
  879. $w,
  880. $h,
  881. $image->getType(),
  882. $image->getBlocks(),
  883. $image->isAnimated()
  884. );
  885. } else {
  886. throw new \Exception(sprintf('Unsupported mode "%s"', $mode));
  887. }
  888. }
  889. /**
  890. * Get image type base on file extension.
  891. *
  892. * @param int $imageFile File path to image.
  893. *
  894. * @return ImageType string Type of image.
  895. */
  896. private function _getImageTypeFromFileName($imageFile)
  897. {
  898. $ext = strtolower((string)pathinfo($imageFile, PATHINFO_EXTENSION));
  899. if ('jpg' === $ext or 'jpeg' === $ext) {
  900. return ImageType::JPEG;
  901. } else if ('gif' === $ext) {
  902. return ImageType::GIF;
  903. } else if ('png' === $ext) {
  904. return ImageType::PNG;
  905. } else if ('wbm' === $ext or 'wbmp' === $ext) {
  906. return ImageType::WBMP;
  907. } else {
  908. return ImageType::UNKNOWN;
  909. }
  910. }
  911. /**
  912. * Resize helper function.
  913. *
  914. * @param Image $image
  915. * @param int $newWidth
  916. * @param int $newHeight
  917. * @param int $targetX
  918. * @param int $targetY
  919. * @param int $srcX
  920. * @param int $srcY
  921. *
  922. */
  923. private function _resize(&$image, $newWidth, $newHeight, $targetX = 0, $targetY = 0, $srcX = 0, $srcY = 0)
  924. {
  925. // $this->_imageCheck();
  926. if ($image->isAnimated()) { // Animated GIF
  927. $gift = new GifHelper();
  928. $blocks = $gift->resize($image->getBlocks(), $newWidth, $newHeight);
  929. // Resize image instance
  930. $image = new Image(
  931. $image->getCore(),
  932. $image->getImageFile(),
  933. $newWidth,
  934. $newHeight,
  935. $image->getType(),
  936. $blocks,
  937. true
  938. );
  939. } else {
  940. // Create blank image
  941. $newImage = Image::createBlank($newWidth, $newHeight);
  942. if (ImageType::PNG === $image->getType()) {
  943. // Preserve PNG transparency
  944. $newImage->fullAlphaMode(true);
  945. }
  946. imagecopyresampled(
  947. $newImage->getCore(),
  948. $image->getCore(),
  949. $targetX,
  950. $targetY,
  951. $srcX,
  952. $srcY,
  953. $newWidth,
  954. $newHeight,
  955. $image->getWidth(),
  956. $image->getHeight()
  957. );
  958. // Free memory of old resource
  959. imagedestroy($image->getCore());
  960. // Resize image instance
  961. $image = new Image(
  962. $newImage->getCore(),
  963. $image->getImageFile(),
  964. $newWidth,
  965. $newHeight,
  966. $image->getType()
  967. );
  968. }
  969. }
  970. /**
  971. * Crop based on entropy.
  972. *
  973. * @param Image $oldImage
  974. * @param $cropW
  975. * @param $cropH
  976. *
  977. * @return array
  978. */
  979. private function _smartCrop($oldImage, $cropW, $cropH){
  980. $image = clone $oldImage;
  981. $this->resizeFit($image, 30, 30);
  982. $origW = $oldImage->getWidth();
  983. $origH = $oldImage->getHeight();
  984. $resizeW = $image->getWidth();
  985. $resizeH = $image->getHeight();
  986. $smallCropW = round(($resizeW / $origW) * $cropW);
  987. $smallCropH = round(($resizeH / $origH) * $cropH);
  988. $step = 1;
  989. for($y = 0; $y < $resizeH-$smallCropH; $y+=$step){
  990. for($x = 0; $x < $resizeW-$smallCropW; $x+=$step){
  991. $hist[$x.'-'.$y] = $this->_entropy($image->histogram(array(array($x, $y), array($smallCropW, $smallCropH))));
  992. }
  993. if($resizeW-$smallCropW <= 0){
  994. $hist['0-'.$y] = $this->_entropy($image->histogram(array(array(0, 0), array($smallCropW, $smallCropH))));
  995. }
  996. }
  997. if($resizeH-$smallCropH <= 0){
  998. $hist['0-0'] = $this->_entropy($image->histogram(array(array(0, 0), array($smallCropW, $smallCropH))));
  999. }
  1000. asort($hist);
  1001. end($hist);
  1002. $pos = key($hist); // last key
  1003. list($x, $y) = explode('-', $pos);
  1004. $x = round($x*($origW / $resizeW));
  1005. $y = round($y*($origH / $resizeH));
  1006. return array($x,$y);
  1007. }
  1008. }