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