image.php 33 KB

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