OC_Image.php 31 KB

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