image.php 32 KB

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