Source for file Image.php

Documentation is available at Image.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * @copyright  Copyright (c) 2004, 2010 David Grudl
  7. 7:  * @license    http://nettephp.com/license  Nette license
  8. 8:  * @link       http://nettephp.com
  9. 9:  * @category   Nette
  10. 10:  * @package    Nette
  11. 11:  */
  12. 12:  
  13. 13:  
  14. 14:  
  15. 15: /**
  16. 16:  * Basic manipulation with images.
  17. 17:  *
  18. 18:  * <code>
  19. 19:  * $image = Image::fromFile('nette.jpg');
  20. 20:  * $image->resize(150, 100);
  21. 21:  * $image->sharpen();
  22. 22:  * $image->send();
  23. 23:  * </code>
  24. 24:  *
  25. 25:  * @copyright  Copyright (c) 2004, 2010 David Grudl
  26. 26:  * @package    Nette
  27. 27:  *
  28. 28:  * @property-read int $width 
  29. 29:  * @property-read int $height 
  30. 30:  * @property-read resource $imageResource 
  31. 31:  */
  32. 32: class Image extends Object
  33. 33: {
  34. 34:     /** {@link resize()} allows enlarging image (it only shrinks images by default) */
  35. 35:     const ENLARGE = 1;
  36. 36:  
  37. 37:     /** {@link resize()} will ignore aspect ratio */
  38. 38:     const STRETCH = 2;
  39. 39:  
  40. 40:     /** {@link resize()} fits in given area */
  41. 41:     const FIT = 0;
  42. 42:  
  43. 43:     /** {@link resize()} fills (and even overflows) given area */
  44. 44:     const FILL = 4;
  45. 45:  
  46. 46:     /**#@+ @int image types {@link send()} */
  47. 47:     const JPEG = IMAGETYPE_JPEG;
  48. 48:     const PNG = IMAGETYPE_PNG;
  49. 49:     const GIF = IMAGETYPE_GIF;
  50. 50:     /**#@-*/
  51. 51:  
  52. 52:     const EMPTY_GIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
  53. 53:  
  54. 54:     /** @var bool */
  55. 55:     public static $useImageMagick FALSE;
  56. 56:  
  57. 57:     /** @var resource */
  58. 58:     private $image;
  59. 59:  
  60. 60:  
  61. 61:  
  62. 62:     /**
  63. 63:      * Returns RGB color.
  64. 64:      * @param  int  red 0..255
  65. 65:      * @param  int  green 0..255
  66. 66:      * @param  int  blue 0..255
  67. 67:      * @param  int  transparency 0..127
  68. 68:      * @return array 
  69. 69:      */
  70. 70:     public static function rgb($red$green$blue$transparency 0)
  71. 71:     {
  72. 72:         return array(
  73. 73:             'red' => max(0min(255(int) $red)),
  74. 74:             'green' => max(0min(255(int) $green)),
  75. 75:             'blue' => max(0min(255(int) $blue)),
  76. 76:             'alpha' => max(0min(127(int) $transparency)),
  77. 77:         );
  78. 78:     }
  79. 79:  
  80. 80:  
  81. 81:  
  82. 82:     /**
  83. 83:      * Opens image from file.
  84. 84:      * @param  string 
  85. 85:      * @param  mixed  detected image format
  86. 86:      * @return Image 
  87. 87:      */
  88. 88:     public static function fromFile($file$format NULL)
  89. 89:     {
  90. 90:         if (!extension_loaded('gd')) {
  91. 91:             throw new Exception("PHP extension GD is not loaded.");
  92. 92:         }
  93. 93:  
  94. 94:         $info @getimagesize($file)// intentionally @
  95. 95:         if (self::$useImageMagick && (empty($info|| $info[0$info[19e5)) // cca 1024x768
  96. 96:             return new ImageMagick($file$format);
  97. 97:         }
  98. 98:  
  99. 99:         switch ($format $info[2]{
  100. 100:         case self::JPEG:
  101. 101:             return new self(imagecreatefromjpeg($file));
  102. 102:  
  103. 103:         case self::PNG:
  104. 104:             return new self(imagecreatefrompng($file));
  105. 105:  
  106. 106:         case self::GIF:
  107. 107:             return new self(imagecreatefromgif($file));
  108. 108:  
  109. 109:         default:
  110. 110:             if (self::$useImageMagick{
  111. 111:                 return new ImageMagick($file$format);
  112. 112:             }
  113. 113:             throw new Exception("Unknown image type or file '$file' not found.");
  114. 114:         }
  115. 115:     }
  116. 116:  
  117. 117:  
  118. 118:  
  119. 119:     /**
  120. 120:      * Create a new image from the image stream in the string.
  121. 121:      * @param  string 
  122. 122:      * @param  mixed  detected image format
  123. 123:      * @return Image 
  124. 124:      */
  125. 125:     public static function fromString($s$format NULL)
  126. 126:     {
  127. 127:         if (!extension_loaded('gd')) {
  128. 128:             throw new Exception("PHP extension GD is not loaded.");
  129. 129:         }
  130. 130:  
  131. 131:         if (strncmp($s"\xff\xd8"2=== 0{
  132. 132:             $format self::JPEG;
  133. 133:  
  134. 134:         elseif (strncmp($s"\x89PNG"4=== 0{
  135. 135:             $format self::PNG;
  136. 136:  
  137. 137:         elseif (strncmp($s"GIF"3=== 0{
  138. 138:             $format self::GIF;
  139. 139:  
  140. 140:         else {
  141. 141:             $format NULL;
  142. 142:         }
  143. 143:         return new self(imagecreatefromstring($s));
  144. 144:     }
  145. 145:  
  146. 146:  
  147. 147:  
  148. 148:     /**
  149. 149:      * Creates blank image.
  150. 150:      * @param  int 
  151. 151:      * @param  int 
  152. 152:      * @param  array 
  153. 153:      * @return Image 
  154. 154:      */
  155. 155:     public static function fromBlank($width$height$color NULL)
  156. 156:     {
  157. 157:         if (!extension_loaded('gd')) {
  158. 158:             throw new Exception("PHP extension GD is not loaded.");
  159. 159:         }
  160. 160:  
  161. 161:         $width = (int) $width;
  162. 162:         $height = (int) $height;
  163. 163:         if ($width || $height 1{
  164. 164:             throw new InvalidArgumentException('Image width and height must be greater than zero.');
  165. 165:         }
  166. 166:  
  167. 167:         $image imagecreatetruecolor($width$height);
  168. 168:         if (is_array($color)) {
  169. 169:             $color += array('alpha' => 0);
  170. 170:             $color imagecolorallocatealpha($image$color['red']$color['green']$color['blue']$color['alpha']);
  171. 171:             imagealphablending($imageFALSE);
  172. 172:             imagefilledrectangle($image00$width 1$height 1$color);
  173. 173:             imagealphablending($imageTRUE);
  174. 174:         }
  175. 175:         return new self($image);
  176. 176:     }
  177. 177:  
  178. 178:  
  179. 179:  
  180. 180:     /**
  181. 181:      * Wraps GD image.
  182. 182:      * @param  resource 
  183. 183:      */
  184. 184:     public function __construct($image)
  185. 185:     {
  186. 186:         $this->setImageResource($image);
  187. 187:     }
  188. 188:  
  189. 189:  
  190. 190:  
  191. 191:     /**
  192. 192:      * Returns image width.
  193. 193:      * @return int 
  194. 194:      */
  195. 195:     public function getWidth()
  196. 196:     {
  197. 197:         return imagesx($this->image);
  198. 198:     }
  199. 199:  
  200. 200:  
  201. 201:  
  202. 202:     /**
  203. 203:      * Returns image height.
  204. 204:      * @return int 
  205. 205:      */
  206. 206:     public function getHeight()
  207. 207:     {
  208. 208:         return imagesy($this->image);
  209. 209:     }
  210. 210:  
  211. 211:  
  212. 212:  
  213. 213:     /**
  214. 214:      * Sets image resource.
  215. 215:      * @param  resource 
  216. 216:      * @return Image  provides a fluent interface
  217. 217:      */
  218. 218:     protected function setImageResource($image)
  219. 219:     {
  220. 220:         if (!is_resource($image|| get_resource_type($image!== 'gd'{
  221. 221:             throw new InvalidArgumentException('Image is not valid.');
  222. 222:         }
  223. 223:         $this->image $image;
  224. 224:         return $this;
  225. 225:     }
  226. 226:  
  227. 227:  
  228. 228:  
  229. 229:     /**
  230. 230:      * Returns image GD resource.
  231. 231:      * @return resource 
  232. 232:      */
  233. 233:     public function getImageResource()
  234. 234:     {
  235. 235:         return $this->image;
  236. 236:     }
  237. 237:  
  238. 238:  
  239. 239:  
  240. 240:     /**
  241. 241:      * Resizes image.
  242. 242:      * @param  mixed  width in pixels or percent
  243. 243:      * @param  mixed  height in pixels or percent
  244. 244:      * @param  int    flags
  245. 245:      * @return Image  provides a fluent interface
  246. 246:      */
  247. 247:     public function resize($width$height$flags self::FIT)
  248. 248:     {
  249. 249:         list($newWidth$newHeightself::calculateSize($this->getWidth()$this->getHeight()$width$height$flags);
  250. 250:  
  251. 251:         if ($newWidth !== $this->getWidth(|| $newHeight !== $this->getHeight()) // resize
  252. 252:             $newImage self::fromBlank($newWidth$newHeightself::RGB(000127))->getImageResource();
  253. 253:             imagecopyresampled(
  254. 254:                 $newImage$this->getImageResource(),
  255. 255:                 0000,
  256. 256:                 $newWidth$newHeight$this->getWidth()$this->getHeight()
  257. 257:             );
  258. 258:             $this->image $newImage;
  259. 259:         }
  260. 260:  
  261. 261:         if ($width || $height 0// flip is processed in two steps for better quality
  262. 262:             $newImage self::fromBlank($newWidth$newHeightself::RGB(000127))->getImageResource();
  263. 263:             imagecopyresampled(
  264. 264:                 $newImage$this->getImageResource(),
  265. 265:                 00$width $newWidth 0$height $newHeight 0,
  266. 266:                 $newWidth$newHeight$width ? -$newWidth $newWidth$height ? -$newHeight $newHeight
  267. 267:             );
  268. 268:             $this->image $newImage;
  269. 269:         }
  270. 270:         return $this;
  271. 271:     }
  272. 272:  
  273. 273:  
  274. 274:  
  275. 275:     /**
  276. 276:      * Calculates dimensions of resized image.
  277. 277:      * @param  mixed  source width
  278. 278:      * @param  mixed  source height
  279. 279:      * @param  mixed  width in pixels or percent
  280. 280:      * @param  mixed  height in pixels or percent
  281. 281:      * @param  int    flags
  282. 282:      * @return array 
  283. 283:      */
  284. 284:     public static function calculateSize($srcWidth$srcHeight$newWidth$newHeight$flags self::FIT)
  285. 285:     {
  286. 286:         if (substr($newWidth-1=== '%'{
  287. 287:             $newWidth round($srcWidth 100 abs($newWidth));
  288. 288:             $flags |= self::ENLARGE;
  289. 289:             $percents TRUE;
  290. 290:         else {
  291. 291:             $newWidth = (int) abs($newWidth);
  292. 292:         }
  293. 293:  
  294. 294:         if (substr($newHeight-1=== '%'{
  295. 295:             $newHeight round($srcHeight 100 abs($newHeight));
  296. 296:             $flags |= empty($percentsself::ENLARGE self::STRETCH;
  297. 297:         else {
  298. 298:             $newHeight = (int) abs($newHeight);
  299. 299:         }
  300. 300:  
  301. 301:         if ($flags self::STRETCH// non-proportional
  302. 302:             if (empty($newWidth|| empty($newHeight)) {
  303. 303:                 throw new InvalidArgumentException('For stretching must be both width and height specified.');
  304. 304:             }
  305. 305:  
  306. 306:             if (($flags self::ENLARGE=== 0{
  307. 307:                 $newWidth round($srcWidth min(1$newWidth $srcWidth));
  308. 308:                 $newHeight round($srcHeight min(1$newHeight $srcHeight));
  309. 309:             }
  310. 310:  
  311. 311:         else {  // proportional
  312. 312:             if (empty($newWidth&& empty($newHeight)) {
  313. 313:                 throw new InvalidArgumentException('At least width or height must be specified.');
  314. 314:             }
  315. 315:  
  316. 316:             $scale array();
  317. 317:             if ($newWidth 0// fit width
  318. 318:                 $scale[$newWidth $srcWidth;
  319. 319:             }
  320. 320:  
  321. 321:             if ($newHeight 0// fit height
  322. 322:                 $scale[$newHeight $srcHeight;
  323. 323:             }
  324. 324:  
  325. 325:             if ($flags self::FILL{
  326. 326:                 $scale array(max($scale));
  327. 327:             }
  328. 328:  
  329. 329:             if (($flags self::ENLARGE=== 0{
  330. 330:                 $scale[1;
  331. 331:             }
  332. 332:  
  333. 333:             $scale min($scale);
  334. 334:             $newWidth round($srcWidth $scale);
  335. 335:             $newHeight round($srcHeight $scale);
  336. 336:         }
  337. 337:  
  338. 338:         return array((int) $newWidth(int) $newHeight);
  339. 339:     }
  340. 340:  
  341. 341:  
  342. 342:  
  343. 343:     /**
  344. 344:      * Crops image.
  345. 345:      * @param  mixed  x-offset in pixels or percent
  346. 346:      * @param  mixed  y-offset in pixels or percent
  347. 347:      * @param  int    width
  348. 348:      * @param  int    height
  349. 349:      * @return Image  provides a fluent interface
  350. 350:      */
  351. 351:     public function crop($left$top$width$height)
  352. 352:     {
  353. 353:         if (substr($left-1=== '%'{
  354. 354:             $left round(($this->getWidth($width100 $left);
  355. 355:         }
  356. 356:  
  357. 357:         if (substr($top-1=== '%'{
  358. 358:             $top round(($this->getHeight($height100 $top);
  359. 359:         }
  360. 360:  
  361. 361:         $left max(0(int) $left);
  362. 362:         $top max(0(int) $top);
  363. 363:         $width min((int) $width$this->getWidth($left);
  364. 364:         $height min((int) $height$this->getHeight($top);
  365. 365:  
  366. 366:         $newImage self::fromBlank($width$heightself::RGB(000127))->getImageResource();
  367. 367:         imagecopy($newImage$this->getImageResource()00$left$top$width$height);
  368. 368:         $this->image $newImage;
  369. 369:         return $this;
  370. 370:     }
  371. 371:  
  372. 372:  
  373. 373:  
  374. 374:     /**
  375. 375:      * Sharpen image.
  376. 376:      * @return Image  provides a fluent interface
  377. 377:      */
  378. 378:     public function sharpen()
  379. 379:     {
  380. 380:         imageconvolution($this->getImageResource()array// my magic numbers ;)
  381. 381:             array-1-1-),
  382. 382:             array-124-),
  383. 383:             array-1-1-),
  384. 384:         )160);
  385. 385:         return $this;
  386. 386:     }
  387. 387:  
  388. 388:  
  389. 389:  
  390. 390:     /**
  391. 391:      * Puts another image into this image.
  392. 392:      * @param  Image 
  393. 393:      * @param  mixed  x-coordinate in pixels or percent
  394. 394:      * @param  mixed  y-coordinate in pixels or percent
  395. 395:      * @param  int  opacity 0..100
  396. 396:      * @return Image  provides a fluent interface
  397. 397:      */
  398. 398:     public function place(Image $image$left 0$top 0$opacity 100)
  399. 399:     {
  400. 400:         $opacity max(0min(100(int) $opacity));
  401. 401:  
  402. 402:         if (substr($left-1=== '%'{
  403. 403:             $left round(($this->getWidth($image->getWidth()) 100 $left);
  404. 404:         }
  405. 405:  
  406. 406:         if (substr($top-1=== '%'{
  407. 407:             $top round(($this->getHeight($image->getHeight()) 100 $top);
  408. 408:         }
  409. 409:  
  410. 410:         if ($opacity === 100{
  411. 411:             imagecopy($this->getImageResource()$image->getImageResource()$left$top00$image->getWidth()$image->getHeight());
  412. 412:  
  413. 413:         elseif ($opacity <> 0{
  414. 414:             imagecopymerge($this->getImageResource()$image->getImageResource()$left$top00$image->getWidth()$image->getHeight()$opacity);
  415. 415:         }
  416. 416:         return $this;
  417. 417:     }
  418. 418:  
  419. 419:  
  420. 420:  
  421. 421:     /**
  422. 422:      * Saves image to the file.
  423. 423:      * @param  string  filename
  424. 424:      * @param  int  quality 0..100 (for JPEG and PNG)
  425. 425:      * @param  int  optional image type
  426. 426:      * @return bool TRUE on success or FALSE on failure.
  427. 427:      */
  428. 428:     public function save($file NULL$quality NULL$type NULL)
  429. 429:     {
  430. 430:         if ($type === NULL{
  431. 431:             switch (strtolower(pathinfo($filePATHINFO_EXTENSION))) {
  432. 432:             case 'jpg':
  433. 433:             case 'jpeg':
  434. 434:                 $type self::JPEG;
  435. 435:                 break;
  436. 436:             case 'png':
  437. 437:                 $type self::PNG;
  438. 438:                 break;
  439. 439:             case 'gif':
  440. 440:                 $type self::GIF;
  441. 441:             }
  442. 442:         }
  443. 443:  
  444. 444:         switch ($type{
  445. 445:         case self::JPEG:
  446. 446:             $quality $quality === NULL 85 max(0min(100(int) $quality));
  447. 447:             return imagejpeg($this->getImageResource()$file$quality);
  448. 448:  
  449. 449:         case self::PNG:
  450. 450:             $quality $quality === NULL max(0min(9(int) $quality));
  451. 451:             return imagepng($this->getImageResource()$file$quality);
  452. 452:  
  453. 453:         case self::GIF:
  454. 454:             return $file === NULL imagegif($this->getImageResource()) imagegif($this->getImageResource()$file)// PHP bug #44591
  455. 455:  
  456. 456:         default:
  457. 457:             throw new Exception("Unsupported image type.");
  458. 458:         }
  459. 459:     }
  460. 460:  
  461. 461:  
  462. 462:  
  463. 463:     /**
  464. 464:      * Outputs image to string.
  465. 465:      * @param  int  image type
  466. 466:      * @param  int  quality 0..100 (for JPEG and PNG)
  467. 467:      * @return string 
  468. 468:      */
  469. 469:     public function toString($type self::JPEG$quality NULL)
  470. 470:     {
  471. 471:         ob_start();
  472. 472:         $this->save(NULL$quality$type);
  473. 473:         return ob_get_clean();
  474. 474:     }
  475. 475:  
  476. 476:  
  477. 477:  
  478. 478:     /**
  479. 479:      * Outputs image to string.
  480. 480:      * @return string 
  481. 481:      */
  482. 482:     public function __toString()
  483. 483:     {
  484. 484:         try {
  485. 485:             return $this->toString();
  486. 486:  
  487. 487:         catch (Exception $e{
  488. 488:             Debug::toStringException($e);
  489. 489:         }
  490. 490:     }
  491. 491:  
  492. 492:  
  493. 493:  
  494. 494:     /**
  495. 495:      * Outputs image to browser.
  496. 496:      * @param  int  image type
  497. 497:      * @param  int  quality 0..100 (for JPEG and PNG)
  498. 498:      * @return bool TRUE on success or FALSE on failure.
  499. 499:      */
  500. 500:     public function send($type self::JPEG$quality NULL)
  501. 501:     {
  502. 502:         if ($type !== self::GIF && $type !== self::PNG && $type !== self::JPEG{
  503. 503:             throw new Exception("Unsupported image type.");
  504. 504:         }
  505. 505:         header('Content-Type: ' image_type_to_mime_type($type));
  506. 506:         return $this->save(NULL$quality$type);
  507. 507:     }
  508. 508:  
  509. 509:  
  510. 510:  
  511. 511:     /**
  512. 512:      * Call to undefined method.
  513. 513:      *
  514. 514:      * @param  string  method name
  515. 515:      * @param  array   arguments
  516. 516:      * @return mixed 
  517. 517:      * @throws MemberAccessException
  518. 518:      */
  519. 519:     public function __call($name$args)
  520. 520:     {
  521. 521:         $function 'image' $name;
  522. 522:         if (function_exists($function)) {
  523. 523:             foreach ($args as $key => $value{
  524. 524:                 if ($value instanceof self{
  525. 525:                     $args[$key$value->getImageResource();
  526. 526:  
  527. 527:                 elseif (is_array($value&& isset($value['red'])) // rgb
  528. 528:                     $args[$keyimagecolorallocatealpha($this->getImageResource()$value['red']$value['green']$value['blue']$value['alpha']);
  529. 529:                 }
  530. 530:             }
  531. 531:             array_unshift($args$this->getImageResource());
  532. 532:  
  533. 533:             $res call_user_func_array($function$args);
  534. 534:             return is_resource($resnew self($res$res;
  535. 535:         }
  536. 536:  
  537. 537:         return parent::__call($name$args);
  538. 538:     }
  539. 539: