Image.php 31 KB

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