OC_Image.php 31 KB

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