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:     /**#@+ 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 Image 
  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 ImageMagick($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 ImageMagick($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:      * @return Image 
  128. 128:      */
  129. 129:     public static function fromString($s)
  130. 130:     {
  131. 131:         return new self(imagecreatefromstring($s));
  132. 132:     }
  133. 133:  
  134. 134:  
  135. 135:  
  136. 136:     /**
  137. 137:      * Creates blank image.
  138. 138:      * @param  int 
  139. 139:      * @param  int 
  140. 140:      * @param  array 
  141. 141:      * @return Image 
  142. 142:      */
  143. 143:     public static function fromBlank($width$height$color NULL)
  144. 144:     {
  145. 145:         if (!extension_loaded('gd')) {
  146. 146:             throw new Exception("PHP extension GD is not loaded.");
  147. 147:         }
  148. 148:  
  149. 149:         $width = (int) $width;
  150. 150:         $height = (int) $height;
  151. 151:         if ($width || $height 1{
  152. 152:             throw new InvalidArgumentException('Image width and height must be greater than zero.');
  153. 153:         }
  154. 154:  
  155. 155:         $image imagecreatetruecolor($width$height);
  156. 156:         if (is_array($color)) {
  157. 157:             $color imagecolorallocate($image$color['red']$color['green']$color['blue']);
  158. 158:             imagefilledrectangle($image00$width$height$color);
  159. 159:         }
  160. 160:         return new self($image);
  161. 161:     }
  162. 162:  
  163. 163:  
  164. 164:  
  165. 165:     /**
  166. 166:      * Wraps GD image.
  167. 167:      * @param  resource 
  168. 168:      */
  169. 169:     public function __construct($image)
  170. 170:     {
  171. 171:         $this->setImageResource($image);
  172. 172:     }
  173. 173:  
  174. 174:  
  175. 175:  
  176. 176:     /**
  177. 177:      * Returns image width.
  178. 178:      * @return int 
  179. 179:      */
  180. 180:     public function getWidth()
  181. 181:     {
  182. 182:         return imagesx($this->image);
  183. 183:     }
  184. 184:  
  185. 185:  
  186. 186:  
  187. 187:     /**
  188. 188:      * Returns image height.
  189. 189:      * @return int 
  190. 190:      */
  191. 191:     public function getHeight()
  192. 192:     {
  193. 193:         return imagesy($this->image);
  194. 194:     }
  195. 195:  
  196. 196:  
  197. 197:  
  198. 198:     /**
  199. 199:      * Sets image resource.
  200. 200:      * @param  resource 
  201. 201:      * @return void 
  202. 202:      */
  203. 203:     protected function setImageResource($image)
  204. 204:     {
  205. 205:         if (!is_resource($image|| get_resource_type($image!== 'gd'{
  206. 206:             throw new InvalidArgumentException('Image is not valid.');
  207. 207:         }
  208. 208:         $this->image $image;
  209. 209:     }
  210. 210:  
  211. 211:  
  212. 212:  
  213. 213:     /**
  214. 214:      * Returns image GD resource.
  215. 215:      * @return resource 
  216. 216:      */
  217. 217:     public function getImageResource()
  218. 218:     {
  219. 219:         return $this->image;
  220. 220:     }
  221. 221:  
  222. 222:  
  223. 223:  
  224. 224:     /**
  225. 225:      * Resizes image.
  226. 226:      * @param  mixed  width in pixels or percent
  227. 227:      * @param  mixed  height in pixels or percent
  228. 228:      * @param  int    flags
  229. 229:      * @return Image  provides a fluent interface
  230. 230:      */
  231. 231:     public function resize($newWidth$newHeight$flags 0)
  232. 232:     {
  233. 233:         list($newWidth$newHeight$this->calculateSize($newWidth$newHeight$flags);
  234. 234:         $newImage imagecreatetruecolor($newWidth$newHeight);
  235. 235:         imagecopyresampled($newImage$this->getImageResource()0000$newWidth$newHeight$this->getWidth()$this->getHeight());
  236. 236:         $this->image $newImage;
  237. 237:         return $this;
  238. 238:     }
  239. 239:  
  240. 240:  
  241. 241:  
  242. 242:     /**
  243. 243:      * Calculates dimensions of resized image.
  244. 244:      * @param  mixed  width in pixels or percent
  245. 245:      * @param  mixed  height in pixels or percent
  246. 246:      * @param  int    flags
  247. 247:      * @return array 
  248. 248:      */
  249. 249:     public function calculateSize($newWidth$newHeight$flags 0)
  250. 250:     {
  251. 251:         $width $this->getWidth();
  252. 252:         $height $this->getHeight();
  253. 253:  
  254. 254:         if (substr($newWidth-1=== '%'{
  255. 255:             $newWidth round($width 100 $newWidth);
  256. 256:             $flags |= self::ENLARGE;
  257. 257:             $percents TRUE;
  258. 258:         else {
  259. 259:             $newWidth = (int) $newWidth;
  260. 260:         }
  261. 261:  
  262. 262:         if (substr($newHeight-1=== '%'{
  263. 263:             $newHeight round($height 100 $newHeight);
  264. 264:             $flags |= empty($percentsself::ENLARGE self::STRETCH;
  265. 265:         else {
  266. 266:             $newHeight = (int) $newHeight;
  267. 267:         }
  268. 268:  
  269. 269:         if ($flags self::STRETCH// non-proportional
  270. 270:             if ($newWidth || $newHeight 1{
  271. 271:                 throw new InvalidArgumentException('For stretching must be both width and height specified.');
  272. 272:             }
  273. 273:  
  274. 274:             if (($flags self::ENLARGE=== 0{
  275. 275:                 $newWidth round($width min(1$newWidth $width));
  276. 276:                 $newHeight round($height min(1$newHeight $height));
  277. 277:             }
  278. 278:  
  279. 279:         else {  // proportional
  280. 280:             if ($newWidth && $newHeight 1{
  281. 281:                 throw new InvalidArgumentException('At least width or height must be specified.');
  282. 282:             }
  283. 283:  
  284. 284:             $scale array();
  285. 285:             if ($newWidth 0// fit width
  286. 286:                 $scale[$newWidth $width;
  287. 287:             }
  288. 288:  
  289. 289:             if ($newHeight 0// fit height
  290. 290:                 $scale[$newHeight $height;
  291. 291:             }
  292. 292:  
  293. 293:             if (($flags self::ENLARGE=== 0{
  294. 294:                 $scale[1;
  295. 295:             }
  296. 296:  
  297. 297:             $scale min($scale);
  298. 298:             $newWidth round($width $scale);
  299. 299:             $newHeight round($height $scale);
  300. 300:         }
  301. 301:  
  302. 302:         return array($newWidth$newHeight);
  303. 303:     }
  304. 304:  
  305. 305:  
  306. 306:  
  307. 307:     /**
  308. 308:      * Crops image.
  309. 309:      * @param  int    x-coordinate
  310. 310:      * @param  int    y-coordinate
  311. 311:      * @param  int    width
  312. 312:      * @param  int    height
  313. 313:      * @return Image  provides a fluent interface
  314. 314:      */
  315. 315:     public function crop($left$top$width$height)
  316. 316:     {
  317. 317:         $left max(0(int) $left);
  318. 318:         $top max(0(int) $top);
  319. 319:         $width min((int) $width$this->getWidth($left);
  320. 320:         $height min((int) $height$this->getHeight($top);
  321. 321:  
  322. 322:         $newImage imagecreatetruecolor($width$height);
  323. 323:         imagecopy($newImage$this->getImageResource()00$left$top$width$height);
  324. 324:         $this->image $newImage;
  325. 325:         return $this;
  326. 326:     }
  327. 327:  
  328. 328:  
  329. 329:  
  330. 330:     /**
  331. 331:      * Sharpen image.
  332. 332:      * @return Image  provides a fluent interface
  333. 333:      */
  334. 334:     public function sharpen()
  335. 335:     {
  336. 336:         imageconvolution($this->getImageResource()array// my magic numbers ;)
  337. 337:             array-1-1-),
  338. 338:             array-124-),
  339. 339:             array-1-1-),
  340. 340:         )160);
  341. 341:         return $this;
  342. 342:     }
  343. 343:  
  344. 344:  
  345. 345:  
  346. 346:     /**
  347. 347:      * Puts another image into this image.
  348. 348:      * @param  Image 
  349. 349:      * @param  mixed  x-coordinate in pixels or percent
  350. 350:      * @param  mixed  y-coordinate in pixels or percent
  351. 351:      * @param  int  opacity 0..100
  352. 352:      * @return Image  provides a fluent interface
  353. 353:      */
  354. 354:     public function place(Image $image$left 0$top 0$opacity 100)
  355. 355:     {
  356. 356:         $opacity max(0min(100(int) $opacity));
  357. 357:  
  358. 358:         if (substr($left-1=== '%'{
  359. 359:             $left round(($this->getWidth($image->getWidth()) 100 $left);
  360. 360:         }
  361. 361:  
  362. 362:         if (substr($top-1=== '%'{
  363. 363:             $top round(($this->getHeight($image->getHeight()) 100 $top);
  364. 364:         }
  365. 365:  
  366. 366:         if ($opacity === 100{
  367. 367:             imagecopy($this->getImageResource()$image->getImageResource()$left$top00$image->getWidth()$image->getHeight());
  368. 368:  
  369. 369:         elseif ($opacity <> 0{
  370. 370:             imagecopymerge($this->getImageResource()$image->getImageResource()$left$top00$image->getWidth()$image->getHeight()$opacity);
  371. 371:         }
  372. 372:         return $this;
  373. 373:     }
  374. 374:  
  375. 375:  
  376. 376:  
  377. 377:     /**
  378. 378:      * Saves image to the file.
  379. 379:      * @param  string  filename
  380. 380:      * @param  int  quality 0..100 (for JPEG and PNG)
  381. 381:      * @param  int  optional image type
  382. 382:      * @return bool TRUE on success or FALSE on failure.
  383. 383:      */
  384. 384:     public function save($file NULL$quality NULL$type NULL)
  385. 385:     {
  386. 386:         if ($type === NULL{
  387. 387:             switch (strtolower(pathinfo($filePATHINFO_EXTENSION))) {
  388. 388:             case 'jpg':
  389. 389:             case 'jpeg':
  390. 390:                 $type self::JPEG;
  391. 391:                 break;
  392. 392:             case 'png':
  393. 393:                 $type self::PNG;
  394. 394:                 break;
  395. 395:             case 'gif':
  396. 396:                 $type self::GIF;
  397. 397:             }
  398. 398:         }
  399. 399:  
  400. 400:         switch ($type{
  401. 401:         case self::JPEG:
  402. 402:             $quality $quality === NULL 85 max(0min(100(int) $quality));
  403. 403:             return imagejpeg($this->getImageResource()$file$quality);
  404. 404:  
  405. 405:         case self::PNG:
  406. 406:             $quality $quality === NULL max(0min(9(int) $quality));
  407. 407:             return imagepng($this->getImageResource()$file$quality);
  408. 408:  
  409. 409:         case self::GIF:
  410. 410:             return imagegif($this->getImageResource()$file);
  411. 411:  
  412. 412:         default:
  413. 413:             throw new Exception("Unsupported image type.");
  414. 414:         }
  415. 415:     }
  416. 416:  
  417. 417:  
  418. 418:  
  419. 419:     /**
  420. 420:      * Outputs image to string.
  421. 421:      * @param  int  image type
  422. 422:      * @param  int  quality 0..100 (for JPEG and PNG)
  423. 423:      * @return string 
  424. 424:      */
  425. 425:     public function toString($type self::JPEG$quality NULL)
  426. 426:     {
  427. 427:         ob_start();
  428. 428:         $this->save(NULL$quality$type);
  429. 429:         return ob_get_clean();
  430. 430:     }
  431. 431:  
  432. 432:  
  433. 433:  
  434. 434:     /**
  435. 435:      * Outputs image to string.
  436. 436:      * @return string 
  437. 437:      */
  438. 438:     public function __toString()
  439. 439:     {
  440. 440:         try {
  441. 441:             return $this->toString();
  442. 442:  
  443. 443:         catch (Exception $e{
  444. 444:             trigger_error($e->getMessage()E_USER_WARNING);
  445. 445:             return '';
  446. 446:         }
  447. 447:     }
  448. 448:  
  449. 449:  
  450. 450:  
  451. 451:     /**
  452. 452:      * Outputs image to browser.
  453. 453:      * @param  int  image type
  454. 454:      * @param  int  quality 0..100 (for JPEG and PNG)
  455. 455:      * @return bool TRUE on success or FALSE on failure.
  456. 456:      */
  457. 457:     public function send($type self::JPEG$quality NULL)
  458. 458:     {
  459. 459:         if ($type !== self::GIF && $type !== self::PNG && $type !== self::JPEG{
  460. 460:             throw new Exception("Unsupported image type.");
  461. 461:         }
  462. 462:         header('Content-Type: ' image_type_to_mime_type($type));
  463. 463:         return $this->save(NULL$quality$type);
  464. 464:     }
  465. 465:  
  466. 466:  
  467. 467:  
  468. 468:     /**
  469. 469:      * Call to undefined method.
  470. 470:      *
  471. 471:      * @param  string  method name
  472. 472:      * @param  array   arguments
  473. 473:      * @return mixed 
  474. 474:      * @throws MemberAccessException
  475. 475:      */
  476. 476:     public function __call($name$args)
  477. 477:     {
  478. 478:         $function 'image' $name;
  479. 479:         if (function_exists($function)) {
  480. 480:             foreach ($args as $key => $value{
  481. 481:                 if ($value instanceof self{
  482. 482:                     $args[$key$value->getImageResource();
  483. 483:  
  484. 484:                 elseif (is_array($value&& isset($value['red'])) // rgb
  485. 485:                     $args[$keyimagecolorallocatealpha($this->getImageResource()$value['red']$value['green']$value['blue']$value['alpha']);
  486. 486:                 }
  487. 487:             }
  488. 488:             array_unshift($args$this->getImageResource());
  489. 489:  
  490. 490:             return call_user_func_array($function$args);
  491. 491:         }
  492. 492:  
  493. 493:         return parent::__call($name$args);
  494. 494:     }
  495. 495: