image.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Thomas Tanghus
  6. * @copyright 2011 Thomas Tanghus <thomas@tanghus.net>
  7. *
  8. * This file is licensed under the Affero General Public License version 3 or
  9. * later.
  10. * See the COPYING-README file.
  11. *
  12. */
  13. /**
  14. * Class for basic image manipulation
  15. */
  16. class OC_Image {
  17. protected $resource = false; // tmp resource.
  18. protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
  19. protected $mimeType = "image/png"; // Default to png
  20. protected $bitDepth = 24;
  21. protected $filePath = null;
  22. private $fileInfo;
  23. /**
  24. * @var \OCP\ILogger
  25. */
  26. private $logger;
  27. /**
  28. * Get mime type for an image file.
  29. *
  30. * @param string|null $filePath The path to a local image file.
  31. * @return string The mime type if the it could be determined, otherwise an empty string.
  32. */
  33. static public function getMimeTypeForFile($filePath) {
  34. // exif_imagetype throws "read error!" if file is less than 12 byte
  35. if ($filePath !== null && filesize($filePath) > 11) {
  36. $imageType = exif_imagetype($filePath);
  37. } else {
  38. $imageType = false;
  39. }
  40. return $imageType ? image_type_to_mime_type($imageType) : '';
  41. }
  42. /**
  43. * Constructor.
  44. *
  45. * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
  46. * an imagecreate* function.
  47. * @param \OCP\ILogger $logger
  48. */
  49. public function __construct($imageRef = null, $logger = null) {
  50. $this->logger = $logger;
  51. if (is_null($logger)) {
  52. $this->logger = \OC::$server->getLogger();
  53. }
  54. if (!extension_loaded('gd') || !function_exists('gd_info')) {
  55. $this->logger->error(__METHOD__ . '(): GD module not installed', array('app' => 'core'));
  56. return false;
  57. }
  58. if (\OC_Util::fileInfoLoaded()) {
  59. $this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
  60. }
  61. if (!is_null($imageRef)) {
  62. $this->load($imageRef);
  63. }
  64. }
  65. /**
  66. * Determine whether the object contains an image resource.
  67. *
  68. * @return bool
  69. */
  70. public function valid() { // apparently you can't name a method 'empty'...
  71. return is_resource($this->resource);
  72. }
  73. /**
  74. * Returns the MIME type of the image or an empty string if no image is loaded.
  75. *
  76. * @return string
  77. */
  78. public function mimeType() {
  79. return $this->valid() ? $this->mimeType : '';
  80. }
  81. /**
  82. * Returns the width of the image or -1 if no image is loaded.
  83. *
  84. * @return int
  85. */
  86. public function width() {
  87. return $this->valid() ? imagesx($this->resource) : -1;
  88. }
  89. /**
  90. * Returns the height of the image or -1 if no image is loaded.
  91. *
  92. * @return int
  93. */
  94. public function height() {
  95. return $this->valid() ? imagesy($this->resource) : -1;
  96. }
  97. /**
  98. * Returns the width when the image orientation is top-left.
  99. *
  100. * @return int
  101. */
  102. public function widthTopLeft() {
  103. $o = $this->getOrientation();
  104. $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
  105. switch ($o) {
  106. case -1:
  107. case 1:
  108. case 2: // Not tested
  109. case 3:
  110. case 4: // Not tested
  111. return $this->width();
  112. case 5: // Not tested
  113. case 6:
  114. case 7: // Not tested
  115. case 8:
  116. return $this->height();
  117. }
  118. return $this->width();
  119. }
  120. /**
  121. * Returns the height when the image orientation is top-left.
  122. *
  123. * @return int
  124. */
  125. public function heightTopLeft() {
  126. $o = $this->getOrientation();
  127. $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
  128. switch ($o) {
  129. case -1:
  130. case 1:
  131. case 2: // Not tested
  132. case 3:
  133. case 4: // Not tested
  134. return $this->height();
  135. case 5: // Not tested
  136. case 6:
  137. case 7: // Not tested
  138. case 8:
  139. return $this->width();
  140. }
  141. return $this->height();
  142. }
  143. /**
  144. * Outputs the image.
  145. *
  146. * @param string $mimeType
  147. * @return bool
  148. */
  149. public function show($mimeType = null) {
  150. if ($mimeType === null) {
  151. $mimeType = $this->mimeType();
  152. }
  153. header('Content-Type: ' . $mimeType);
  154. return $this->_output(null, $mimeType);
  155. }
  156. /**
  157. * Saves the image.
  158. *
  159. * @param string $filePath
  160. * @param string $mimeType
  161. * @return bool
  162. */
  163. public function save($filePath = null, $mimeType = null) {
  164. if ($mimeType === null) {
  165. $mimeType = $this->mimeType();
  166. }
  167. if ($filePath === null && $this->filePath === null) {
  168. $this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
  169. return false;
  170. } elseif ($filePath === null && $this->filePath !== null) {
  171. $filePath = $this->filePath;
  172. }
  173. return $this->_output($filePath, $mimeType);
  174. }
  175. /**
  176. * Outputs/saves the image.
  177. *
  178. * @param string $filePath
  179. * @param string $mimeType
  180. * @return bool
  181. * @throws Exception
  182. */
  183. private function _output($filePath = null, $mimeType = null) {
  184. if ($filePath) {
  185. if (!file_exists(dirname($filePath)))
  186. mkdir(dirname($filePath), 0777, true);
  187. if (!is_writable(dirname($filePath))) {
  188. $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
  189. return false;
  190. } elseif (is_writable(dirname($filePath)) && file_exists($filePath) && !is_writable($filePath)) {
  191. $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
  192. return false;
  193. }
  194. }
  195. if (!$this->valid()) {
  196. return false;
  197. }
  198. $imageType = $this->imageType;
  199. if ($mimeType !== null) {
  200. switch ($mimeType) {
  201. case 'image/gif':
  202. $imageType = IMAGETYPE_GIF;
  203. break;
  204. case 'image/jpeg':
  205. $imageType = IMAGETYPE_JPEG;
  206. break;
  207. case 'image/png':
  208. $imageType = IMAGETYPE_PNG;
  209. break;
  210. case 'image/x-xbitmap':
  211. $imageType = IMAGETYPE_XBM;
  212. break;
  213. case 'image/bmp':
  214. $imageType = IMAGETYPE_BMP;
  215. break;
  216. default:
  217. throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
  218. }
  219. }
  220. switch ($imageType) {
  221. case IMAGETYPE_GIF:
  222. $retVal = imagegif($this->resource, $filePath);
  223. break;
  224. case IMAGETYPE_JPEG:
  225. $retVal = imagejpeg($this->resource, $filePath);
  226. break;
  227. case IMAGETYPE_PNG:
  228. $retVal = imagepng($this->resource, $filePath);
  229. break;
  230. case IMAGETYPE_XBM:
  231. if (function_exists('imagexbm')) {
  232. $retVal = imagexbm($this->resource, $filePath);
  233. } else {
  234. throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
  235. }
  236. break;
  237. case IMAGETYPE_WBMP:
  238. $retVal = imagewbmp($this->resource, $filePath);
  239. break;
  240. case IMAGETYPE_BMP:
  241. $retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
  242. break;
  243. default:
  244. $retVal = imagepng($this->resource, $filePath);
  245. }
  246. return $retVal;
  247. }
  248. /**
  249. * Prints the image when called as $image().
  250. */
  251. public function __invoke() {
  252. return $this->show();
  253. }
  254. /**
  255. * @return resource Returns the image resource in any.
  256. */
  257. public function resource() {
  258. return $this->resource;
  259. }
  260. /**
  261. * @return string Returns the raw image data.
  262. */
  263. function data() {
  264. ob_start();
  265. switch ($this->mimeType) {
  266. case "image/png":
  267. $res = imagepng($this->resource);
  268. break;
  269. case "image/jpeg":
  270. $res = imagejpeg($this->resource);
  271. break;
  272. case "image/gif":
  273. $res = imagegif($this->resource);
  274. break;
  275. default:
  276. $res = imagepng($this->resource);
  277. $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
  278. break;
  279. }
  280. if (!$res) {
  281. $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
  282. }
  283. return ob_get_clean();
  284. }
  285. /**
  286. * @return string - base64 encoded, which is suitable for embedding in a VCard.
  287. */
  288. function __toString() {
  289. return base64_encode($this->data());
  290. }
  291. /**
  292. * (I'm open for suggestions on better method name ;)
  293. * Get the orientation based on EXIF data.
  294. *
  295. * @return int The orientation or -1 if no EXIF data is available.
  296. */
  297. public function getOrientation() {
  298. if ($this->imageType !== IMAGETYPE_JPEG) {
  299. $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
  300. return -1;
  301. }
  302. if (!is_callable('exif_read_data')) {
  303. $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
  304. return -1;
  305. }
  306. if (!$this->valid()) {
  307. $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
  308. return -1;
  309. }
  310. if (is_null($this->filePath) || !is_readable($this->filePath)) {
  311. $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
  312. return -1;
  313. }
  314. $exif = @exif_read_data($this->filePath, 'IFD0');
  315. if (!$exif) {
  316. return -1;
  317. }
  318. if (!isset($exif['Orientation'])) {
  319. return -1;
  320. }
  321. return $exif['Orientation'];
  322. }
  323. /**
  324. * (I'm open for suggestions on better method name ;)
  325. * Fixes orientation based on EXIF data.
  326. *
  327. * @return bool.
  328. */
  329. public function fixOrientation() {
  330. $o = $this->getOrientation();
  331. $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
  332. $rotate = 0;
  333. $flip = false;
  334. switch ($o) {
  335. case -1:
  336. return false; //Nothing to fix
  337. case 1:
  338. $rotate = 0;
  339. break;
  340. case 2:
  341. $rotate = 0;
  342. $flip = true;
  343. break;
  344. case 3:
  345. $rotate = 180;
  346. break;
  347. case 4:
  348. $rotate = 180;
  349. $flip = true;
  350. break;
  351. case 5:
  352. $rotate = 90;
  353. $flip = true;
  354. break;
  355. case 6:
  356. $rotate = 270;
  357. break;
  358. case 7:
  359. $rotate = 270;
  360. $flip = true;
  361. break;
  362. case 8:
  363. $rotate = 90;
  364. break;
  365. }
  366. if($flip && function_exists('imageflip')) {
  367. imageflip($this->resource, IMG_FLIP_HORIZONTAL);
  368. }
  369. if ($rotate) {
  370. $res = imagerotate($this->resource, $rotate, 0);
  371. if ($res) {
  372. if (imagealphablending($res, true)) {
  373. if (imagesavealpha($res, true)) {
  374. imagedestroy($this->resource);
  375. $this->resource = $res;
  376. return true;
  377. } else {
  378. $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core'));
  379. return false;
  380. }
  381. } else {
  382. $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
  383. return false;
  384. }
  385. } else {
  386. $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core'));
  387. return false;
  388. }
  389. }
  390. return false;
  391. }
  392. /**
  393. * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function.
  394. *
  395. * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle ).
  396. * @return resource|false An image resource or false on error
  397. */
  398. public function load($imageRef) {
  399. if (is_resource($imageRef)) {
  400. if (get_resource_type($imageRef) == 'gd') {
  401. $this->resource = $imageRef;
  402. return $this->resource;
  403. } elseif (in_array(get_resource_type($imageRef), array('file', 'stream'))) {
  404. return $this->loadFromFileHandle($imageRef);
  405. }
  406. } elseif ($this->loadFromBase64($imageRef) !== false) {
  407. return $this->resource;
  408. } elseif ($this->loadFromFile($imageRef) !== false) {
  409. return $this->resource;
  410. } elseif ($this->loadFromData($imageRef) !== false) {
  411. return $this->resource;
  412. }
  413. $this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
  414. return false;
  415. }
  416. /**
  417. * Loads an image from an open file handle.
  418. * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
  419. *
  420. * @param resource $handle
  421. * @return resource|false An image resource or false on error
  422. */
  423. public function loadFromFileHandle($handle) {
  424. $contents = stream_get_contents($handle);
  425. if ($this->loadFromData($contents)) {
  426. return $this->resource;
  427. }
  428. return false;
  429. }
  430. /**
  431. * Loads an image from a local file.
  432. *
  433. * @param bool|string $imagePath The path to a local file.
  434. * @return bool|resource An image resource or false on error
  435. */
  436. public function loadFromFile($imagePath = false) {
  437. // exif_imagetype throws "read error!" if file is less than 12 byte
  438. if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
  439. return false;
  440. }
  441. $iType = exif_imagetype($imagePath);
  442. switch ($iType) {
  443. case IMAGETYPE_GIF:
  444. if (imagetypes() & IMG_GIF) {
  445. $this->resource = imagecreatefromgif($imagePath);
  446. // Preserve transparency
  447. imagealphablending($this->resource, true);
  448. imagesavealpha($this->resource, true);
  449. } else {
  450. $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
  451. }
  452. break;
  453. case IMAGETYPE_JPEG:
  454. if (imagetypes() & IMG_JPG) {
  455. $this->resource = imagecreatefromjpeg($imagePath);
  456. } else {
  457. $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
  458. }
  459. break;
  460. case IMAGETYPE_PNG:
  461. if (imagetypes() & IMG_PNG) {
  462. $this->resource = imagecreatefrompng($imagePath);
  463. // Preserve transparency
  464. imagealphablending($this->resource, true);
  465. imagesavealpha($this->resource, true);
  466. } else {
  467. $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
  468. }
  469. break;
  470. case IMAGETYPE_XBM:
  471. if (imagetypes() & IMG_XPM) {
  472. $this->resource = imagecreatefromxbm($imagePath);
  473. } else {
  474. $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
  475. }
  476. break;
  477. case IMAGETYPE_WBMP:
  478. if (imagetypes() & IMG_WBMP) {
  479. $this->resource = imagecreatefromwbmp($imagePath);
  480. } else {
  481. $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
  482. }
  483. break;
  484. case IMAGETYPE_BMP:
  485. $this->resource = $this->imagecreatefrombmp($imagePath);
  486. break;
  487. /*
  488. case IMAGETYPE_TIFF_II: // (intel byte order)
  489. break;
  490. case IMAGETYPE_TIFF_MM: // (motorola byte order)
  491. break;
  492. case IMAGETYPE_JPC:
  493. break;
  494. case IMAGETYPE_JP2:
  495. break;
  496. case IMAGETYPE_JPX:
  497. break;
  498. case IMAGETYPE_JB2:
  499. break;
  500. case IMAGETYPE_SWC:
  501. break;
  502. case IMAGETYPE_IFF:
  503. break;
  504. case IMAGETYPE_ICO:
  505. break;
  506. case IMAGETYPE_SWF:
  507. break;
  508. case IMAGETYPE_PSD:
  509. break;
  510. */
  511. default:
  512. // this is mostly file created from encrypted file
  513. $this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
  514. $iType = IMAGETYPE_PNG;
  515. $this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
  516. break;
  517. }
  518. if ($this->valid()) {
  519. $this->imageType = $iType;
  520. $this->mimeType = image_type_to_mime_type($iType);
  521. $this->filePath = $imagePath;
  522. }
  523. return $this->resource;
  524. }
  525. /**
  526. * Loads an image from a string of data.
  527. *
  528. * @param string $str A string of image data as read from a file.
  529. * @return bool|resource An image resource or false on error
  530. */
  531. public function loadFromData($str) {
  532. if (is_resource($str)) {
  533. return false;
  534. }
  535. $this->resource = @imagecreatefromstring($str);
  536. if ($this->fileInfo) {
  537. $this->mimeType = $this->fileInfo->buffer($str);
  538. }
  539. if (is_resource($this->resource)) {
  540. imagealphablending($this->resource, false);
  541. imagesavealpha($this->resource, true);
  542. }
  543. if (!$this->resource) {
  544. $this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
  545. return false;
  546. }
  547. return $this->resource;
  548. }
  549. /**
  550. * Loads an image from a base64 encoded string.
  551. *
  552. * @param string $str A string base64 encoded string of image data.
  553. * @return bool|resource An image resource or false on error
  554. */
  555. public function loadFromBase64($str) {
  556. if (!is_string($str)) {
  557. return false;
  558. }
  559. $data = base64_decode($str);
  560. if ($data) { // try to load from string data
  561. $this->resource = @imagecreatefromstring($data);
  562. if ($this->fileInfo) {
  563. $this->mimeType = $this->fileInfo->buffer($data);
  564. }
  565. if (!$this->resource) {
  566. $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
  567. return false;
  568. }
  569. return $this->resource;
  570. } else {
  571. return false;
  572. }
  573. }
  574. /**
  575. * Create a new image from file or URL
  576. *
  577. * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
  578. * @version 1.00
  579. * @param string $fileName <p>
  580. * Path to the BMP image.
  581. * </p>
  582. * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
  583. */
  584. private function imagecreatefrombmp($fileName) {
  585. if (!($fh = fopen($fileName, 'rb'))) {
  586. $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
  587. return false;
  588. }
  589. // read file header
  590. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  591. // check for bitmap
  592. if ($meta['type'] != 19778) {
  593. fclose($fh);
  594. $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
  595. return false;
  596. }
  597. // read image header
  598. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  599. // read additional 16bit header
  600. if ($meta['bits'] == 16) {
  601. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  602. }
  603. // set bytes and padding
  604. $meta['bytes'] = $meta['bits'] / 8;
  605. $this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
  606. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
  607. if ($meta['decal'] == 4) {
  608. $meta['decal'] = 0;
  609. }
  610. // obtain imagesize
  611. if ($meta['imagesize'] < 1) {
  612. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  613. // in rare cases filesize is equal to offset so we need to read physical size
  614. if ($meta['imagesize'] < 1) {
  615. $meta['imagesize'] = @filesize($fileName) - $meta['offset'];
  616. if ($meta['imagesize'] < 1) {
  617. fclose($fh);
  618. $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
  619. return false;
  620. }
  621. }
  622. }
  623. // calculate colors
  624. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  625. // read color palette
  626. $palette = array();
  627. if ($meta['bits'] < 16) {
  628. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  629. // in rare cases the color value is signed
  630. if ($palette[1] < 0) {
  631. foreach ($palette as $i => $color) {
  632. $palette[$i] = $color + 16777216;
  633. }
  634. }
  635. }
  636. // create gd image
  637. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  638. if ($im == false) {
  639. fclose($fh);
  640. $this->logger->warning(
  641. 'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
  642. array('app' => 'core'));
  643. return false;
  644. }
  645. $data = fread($fh, $meta['imagesize']);
  646. $p = 0;
  647. $vide = chr(0);
  648. $y = $meta['height'] - 1;
  649. $error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
  650. // loop through the image data beginning with the lower left corner
  651. while ($y >= 0) {
  652. $x = 0;
  653. while ($x < $meta['width']) {
  654. switch ($meta['bits']) {
  655. case 32:
  656. case 24:
  657. if (!($part = substr($data, $p, 3))) {
  658. $this->logger->warning($error, array('app' => 'core'));
  659. return $im;
  660. }
  661. $color = unpack('V', $part . $vide);
  662. break;
  663. case 16:
  664. if (!($part = substr($data, $p, 2))) {
  665. fclose($fh);
  666. $this->logger->warning($error, array('app' => 'core'));
  667. return $im;
  668. }
  669. $color = unpack('v', $part);
  670. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
  671. break;
  672. case 8:
  673. $color = unpack('n', $vide . substr($data, $p, 1));
  674. $color[1] = $palette[$color[1] + 1];
  675. break;
  676. case 4:
  677. $color = unpack('n', $vide . substr($data, floor($p), 1));
  678. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  679. $color[1] = $palette[$color[1] + 1];
  680. break;
  681. case 1:
  682. $color = unpack('n', $vide . substr($data, floor($p), 1));
  683. switch (($p * 8) % 8) {
  684. case 0:
  685. $color[1] = $color[1] >> 7;
  686. break;
  687. case 1:
  688. $color[1] = ($color[1] & 0x40) >> 6;
  689. break;
  690. case 2:
  691. $color[1] = ($color[1] & 0x20) >> 5;
  692. break;
  693. case 3:
  694. $color[1] = ($color[1] & 0x10) >> 4;
  695. break;
  696. case 4:
  697. $color[1] = ($color[1] & 0x8) >> 3;
  698. break;
  699. case 5:
  700. $color[1] = ($color[1] & 0x4) >> 2;
  701. break;
  702. case 6:
  703. $color[1] = ($color[1] & 0x2) >> 1;
  704. break;
  705. case 7:
  706. $color[1] = ($color[1] & 0x1);
  707. break;
  708. }
  709. $color[1] = $palette[$color[1] + 1];
  710. break;
  711. default:
  712. fclose($fh);
  713. $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
  714. return false;
  715. }
  716. imagesetpixel($im, $x, $y, $color[1]);
  717. $x++;
  718. $p += $meta['bytes'];
  719. }
  720. $y--;
  721. $p += $meta['decal'];
  722. }
  723. fclose($fh);
  724. return $im;
  725. }
  726. /**
  727. * Resizes the image preserving ratio.
  728. *
  729. * @param integer $maxSize The maximum size of either the width or height.
  730. * @return bool
  731. */
  732. public function resize($maxSize) {
  733. if (!$this->valid()) {
  734. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  735. return false;
  736. }
  737. $widthOrig = imageSX($this->resource);
  738. $heightOrig = imageSY($this->resource);
  739. $ratioOrig = $widthOrig / $heightOrig;
  740. if ($ratioOrig > 1) {
  741. $newHeight = round($maxSize / $ratioOrig);
  742. $newWidth = $maxSize;
  743. } else {
  744. $newWidth = round($maxSize * $ratioOrig);
  745. $newHeight = $maxSize;
  746. }
  747. $this->preciseResize(round($newWidth), round($newHeight));
  748. return true;
  749. }
  750. /**
  751. * @param int $width
  752. * @param int $height
  753. * @return bool
  754. */
  755. public function preciseResize($width, $height) {
  756. if (!$this->valid()) {
  757. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  758. return false;
  759. }
  760. $widthOrig = imageSX($this->resource);
  761. $heightOrig = imageSY($this->resource);
  762. $process = imagecreatetruecolor($width, $height);
  763. if ($process == false) {
  764. $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
  765. imagedestroy($process);
  766. return false;
  767. }
  768. // preserve transparency
  769. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  770. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  771. imagealphablending($process, false);
  772. imagesavealpha($process, true);
  773. }
  774. imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
  775. if ($process == false) {
  776. $this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
  777. imagedestroy($process);
  778. return false;
  779. }
  780. imagedestroy($this->resource);
  781. $this->resource = $process;
  782. return true;
  783. }
  784. /**
  785. * Crops the image to the middle square. If the image is already square it just returns.
  786. *
  787. * @param int $size maximum size for the result (optional)
  788. * @return bool for success or failure
  789. */
  790. public function centerCrop($size = 0) {
  791. if (!$this->valid()) {
  792. $this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
  793. return false;
  794. }
  795. $widthOrig = imageSX($this->resource);
  796. $heightOrig = imageSY($this->resource);
  797. if ($widthOrig === $heightOrig and $size == 0) {
  798. return true;
  799. }
  800. $ratioOrig = $widthOrig / $heightOrig;
  801. $width = $height = min($widthOrig, $heightOrig);
  802. if ($ratioOrig > 1) {
  803. $x = ($widthOrig / 2) - ($width / 2);
  804. $y = 0;
  805. } else {
  806. $y = ($heightOrig / 2) - ($height / 2);
  807. $x = 0;
  808. }
  809. if ($size > 0) {
  810. $targetWidth = $size;
  811. $targetHeight = $size;
  812. } else {
  813. $targetWidth = $width;
  814. $targetHeight = $height;
  815. }
  816. $process = imagecreatetruecolor($targetWidth, $targetHeight);
  817. if ($process == false) {
  818. $this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
  819. imagedestroy($process);
  820. return false;
  821. }
  822. // preserve transparency
  823. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  824. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  825. imagealphablending($process, false);
  826. imagesavealpha($process, true);
  827. }
  828. imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
  829. if ($process == false) {
  830. $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
  831. imagedestroy($process);
  832. return false;
  833. }
  834. imagedestroy($this->resource);
  835. $this->resource = $process;
  836. return true;
  837. }
  838. /**
  839. * Crops the image from point $x$y with dimension $wx$h.
  840. *
  841. * @param int $x Horizontal position
  842. * @param int $y Vertical position
  843. * @param int $w Width
  844. * @param int $h Height
  845. * @return bool for success or failure
  846. */
  847. public function crop($x, $y, $w, $h) {
  848. if (!$this->valid()) {
  849. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  850. return false;
  851. }
  852. $process = imagecreatetruecolor($w, $h);
  853. if ($process == false) {
  854. $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
  855. imagedestroy($process);
  856. return false;
  857. }
  858. // preserve transparency
  859. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  860. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  861. imagealphablending($process, false);
  862. imagesavealpha($process, true);
  863. }
  864. imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
  865. if ($process == false) {
  866. $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
  867. imagedestroy($process);
  868. return false;
  869. }
  870. imagedestroy($this->resource);
  871. $this->resource = $process;
  872. return true;
  873. }
  874. /**
  875. * Resizes the image to fit within a boundary while preserving ratio.
  876. *
  877. * @param integer $maxWidth
  878. * @param integer $maxHeight
  879. * @return bool
  880. */
  881. public function fitIn($maxWidth, $maxHeight) {
  882. if (!$this->valid()) {
  883. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  884. return false;
  885. }
  886. $widthOrig = imageSX($this->resource);
  887. $heightOrig = imageSY($this->resource);
  888. $ratio = $widthOrig / $heightOrig;
  889. $newWidth = min($maxWidth, $ratio * $maxHeight);
  890. $newHeight = min($maxHeight, $maxWidth / $ratio);
  891. $this->preciseResize(round($newWidth), round($newHeight));
  892. return true;
  893. }
  894. public function destroy() {
  895. if ($this->valid()) {
  896. imagedestroy($this->resource);
  897. }
  898. $this->resource = null;
  899. }
  900. public function __destruct() {
  901. $this->destroy();
  902. }
  903. }
  904. if (!function_exists('imagebmp')) {
  905. /**
  906. * Output a BMP image to either the browser or a file
  907. *
  908. * @link http://www.ugia.cn/wp-data/imagebmp.php
  909. * @author legend <legendsky@hotmail.com>
  910. * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
  911. * @author mgutt <marc@gutt.it>
  912. * @version 1.00
  913. * @param string $fileName [optional] <p>The path to save the file to.</p>
  914. * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
  915. * @param int $compression [optional]
  916. * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
  917. */
  918. function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
  919. if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
  920. $bit = 24;
  921. } else if ($bit == 32) {
  922. $bit = 24;
  923. }
  924. $bits = pow(2, $bit);
  925. imagetruecolortopalette($im, true, $bits);
  926. $width = imagesx($im);
  927. $height = imagesy($im);
  928. $colorsNum = imagecolorstotal($im);
  929. $rgbQuad = '';
  930. if ($bit <= 8) {
  931. for ($i = 0; $i < $colorsNum; $i++) {
  932. $colors = imagecolorsforindex($im, $i);
  933. $rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
  934. }
  935. $bmpData = '';
  936. if ($compression == 0 || $bit < 8) {
  937. $compression = 0;
  938. $extra = '';
  939. $padding = 4 - ceil($width / (8 / $bit)) % 4;
  940. if ($padding % 4 != 0) {
  941. $extra = str_repeat("\0", $padding);
  942. }
  943. for ($j = $height - 1; $j >= 0; $j--) {
  944. $i = 0;
  945. while ($i < $width) {
  946. $bin = 0;
  947. $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
  948. for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
  949. $index = imagecolorat($im, $i, $j);
  950. $bin |= $index << $k;
  951. $i++;
  952. }
  953. $bmpData .= chr($bin);
  954. }
  955. $bmpData .= $extra;
  956. }
  957. } // RLE8
  958. else if ($compression == 1 && $bit == 8) {
  959. for ($j = $height - 1; $j >= 0; $j--) {
  960. $lastIndex = "\0";
  961. $sameNum = 0;
  962. for ($i = 0; $i <= $width; $i++) {
  963. $index = imagecolorat($im, $i, $j);
  964. if ($index !== $lastIndex || $sameNum > 255) {
  965. if ($sameNum != 0) {
  966. $bmpData .= chr($sameNum) . chr($lastIndex);
  967. }
  968. $lastIndex = $index;
  969. $sameNum = 1;
  970. } else {
  971. $sameNum++;
  972. }
  973. }
  974. $bmpData .= "\0\0";
  975. }
  976. $bmpData .= "\0\1";
  977. }
  978. $sizeQuad = strlen($rgbQuad);
  979. $sizeData = strlen($bmpData);
  980. } else {
  981. $extra = '';
  982. $padding = 4 - ($width * ($bit / 8)) % 4;
  983. if ($padding % 4 != 0) {
  984. $extra = str_repeat("\0", $padding);
  985. }
  986. $bmpData = '';
  987. for ($j = $height - 1; $j >= 0; $j--) {
  988. for ($i = 0; $i < $width; $i++) {
  989. $index = imagecolorat($im, $i, $j);
  990. $colors = imagecolorsforindex($im, $index);
  991. if ($bit == 16) {
  992. $bin = 0 << $bit;
  993. $bin |= ($colors['red'] >> 3) << 10;
  994. $bin |= ($colors['green'] >> 3) << 5;
  995. $bin |= $colors['blue'] >> 3;
  996. $bmpData .= pack("v", $bin);
  997. } else {
  998. $bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
  999. }
  1000. }
  1001. $bmpData .= $extra;
  1002. }
  1003. $sizeQuad = 0;
  1004. $sizeData = strlen($bmpData);
  1005. $colorsNum = 0;
  1006. }
  1007. $fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
  1008. $infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
  1009. if ($fileName != '') {
  1010. $fp = fopen($fileName, 'wb');
  1011. fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
  1012. fclose($fp);
  1013. return true;
  1014. }
  1015. echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
  1016. return true;
  1017. }
  1018. }
  1019. if (!function_exists('exif_imagetype')) {
  1020. /**
  1021. * Workaround if exif_imagetype does not exist
  1022. *
  1023. * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
  1024. * @param string $fileName
  1025. * @return string|boolean
  1026. */
  1027. function exif_imagetype($fileName) {
  1028. if (($info = getimagesize($fileName)) !== false) {
  1029. return $info[2];
  1030. }
  1031. return false;
  1032. }
  1033. }