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