1
0

image.php 34 KB

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