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