OC_Image.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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. /**
  362. * (I'm open for suggestions on better method name ;)
  363. * Get the orientation based on EXIF data.
  364. *
  365. * @return int The orientation or -1 if no EXIF data is available.
  366. */
  367. public function getOrientation(): int {
  368. if ($this->exif !== null) {
  369. return $this->exif['Orientation'];
  370. }
  371. if ($this->imageType !== IMAGETYPE_JPEG) {
  372. $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', ['app' => 'core']);
  373. return -1;
  374. }
  375. if (!is_callable('exif_read_data')) {
  376. $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', ['app' => 'core']);
  377. return -1;
  378. }
  379. if (!$this->valid()) {
  380. $this->logger->debug('OC_Image->fixOrientation() No image loaded.', ['app' => 'core']);
  381. return -1;
  382. }
  383. if (is_null($this->filePath) || !is_readable($this->filePath)) {
  384. $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', ['app' => 'core']);
  385. return -1;
  386. }
  387. $exif = @exif_read_data($this->filePath, 'IFD0');
  388. if (!$exif) {
  389. return -1;
  390. }
  391. if (!isset($exif['Orientation'])) {
  392. return -1;
  393. }
  394. $this->exif = $exif;
  395. return $exif['Orientation'];
  396. }
  397. public function readExif($data): void {
  398. if (!is_callable('exif_read_data')) {
  399. $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', ['app' => 'core']);
  400. return;
  401. }
  402. if (!$this->valid()) {
  403. $this->logger->debug('OC_Image->fixOrientation() No image loaded.', ['app' => 'core']);
  404. return;
  405. }
  406. $exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
  407. if (!$exif) {
  408. return;
  409. }
  410. if (!isset($exif['Orientation'])) {
  411. return;
  412. }
  413. $this->exif = $exif;
  414. }
  415. /**
  416. * (I'm open for suggestions on better method name ;)
  417. * Fixes orientation based on EXIF data.
  418. *
  419. * @return bool
  420. */
  421. public function fixOrientation(): bool {
  422. if (!$this->valid()) {
  423. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  424. return false;
  425. }
  426. $o = $this->getOrientation();
  427. $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, ['app' => 'core']);
  428. $rotate = 0;
  429. $flip = false;
  430. switch ($o) {
  431. case -1:
  432. return false; //Nothing to fix
  433. case 1:
  434. $rotate = 0;
  435. break;
  436. case 2:
  437. $rotate = 0;
  438. $flip = true;
  439. break;
  440. case 3:
  441. $rotate = 180;
  442. break;
  443. case 4:
  444. $rotate = 180;
  445. $flip = true;
  446. break;
  447. case 5:
  448. $rotate = 90;
  449. $flip = true;
  450. break;
  451. case 6:
  452. $rotate = 270;
  453. break;
  454. case 7:
  455. $rotate = 270;
  456. $flip = true;
  457. break;
  458. case 8:
  459. $rotate = 90;
  460. break;
  461. }
  462. if ($flip && function_exists('imageflip')) {
  463. imageflip($this->resource, IMG_FLIP_HORIZONTAL);
  464. }
  465. if ($rotate) {
  466. $res = imagerotate($this->resource, $rotate, 0);
  467. if ($res) {
  468. if (imagealphablending($res, true)) {
  469. if (imagesavealpha($res, true)) {
  470. imagedestroy($this->resource);
  471. $this->resource = $res;
  472. return true;
  473. } else {
  474. $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', ['app' => 'core']);
  475. return false;
  476. }
  477. } else {
  478. $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', ['app' => 'core']);
  479. return false;
  480. }
  481. } else {
  482. $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', ['app' => 'core']);
  483. return false;
  484. }
  485. }
  486. return false;
  487. }
  488. /**
  489. * Loads an image from an open file handle.
  490. * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
  491. *
  492. * @param resource $handle
  493. * @return \GdImage|false An image resource or false on error
  494. */
  495. public function loadFromFileHandle($handle) {
  496. $contents = stream_get_contents($handle);
  497. if ($this->loadFromData($contents)) {
  498. return $this->resource;
  499. }
  500. return false;
  501. }
  502. /**
  503. * Check if allocating an image with the given size is allowed.
  504. *
  505. * @param int $width The image width.
  506. * @param int $height The image height.
  507. * @return bool true if allocating is allowed, false otherwise
  508. */
  509. private function checkImageMemory($width, $height) {
  510. $memory_limit = $this->config->getSystemValueInt('preview_max_memory', self::DEFAULT_MEMORY_LIMIT);
  511. if ($memory_limit < 0) {
  512. // Not limited.
  513. return true;
  514. }
  515. // Assume 32 bits per pixel.
  516. if ($width * $height * 4 > $memory_limit * 1024 * 1024) {
  517. $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.');
  518. return false;
  519. }
  520. return true;
  521. }
  522. /**
  523. * Check if loading an image file from the given path is allowed.
  524. *
  525. * @param string $path The path to a local file.
  526. * @return bool true if allocating is allowed, false otherwise
  527. */
  528. private function checkImageSize($path) {
  529. $size = @getimagesize($path);
  530. if (!$size) {
  531. return false;
  532. }
  533. $width = $size[0];
  534. $height = $size[1];
  535. if (!$this->checkImageMemory($width, $height)) {
  536. return false;
  537. }
  538. return true;
  539. }
  540. /**
  541. * Check if loading an image from the given data is allowed.
  542. *
  543. * @param string $data A string of image data as read from a file.
  544. * @return bool true if allocating is allowed, false otherwise
  545. */
  546. private function checkImageDataSize($data) {
  547. $size = @getimagesizefromstring($data);
  548. if (!$size) {
  549. return false;
  550. }
  551. $width = $size[0];
  552. $height = $size[1];
  553. if (!$this->checkImageMemory($width, $height)) {
  554. return false;
  555. }
  556. return true;
  557. }
  558. /**
  559. * Loads an image from a local file.
  560. *
  561. * @param bool|string $imagePath The path to a local file.
  562. * @return bool|\GdImage An image resource or false on error
  563. */
  564. public function loadFromFile($imagePath = false) {
  565. // exif_imagetype throws "read error!" if file is less than 12 byte
  566. if (is_bool($imagePath) || !@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
  567. return false;
  568. }
  569. $iType = exif_imagetype($imagePath);
  570. switch ($iType) {
  571. case IMAGETYPE_GIF:
  572. if (imagetypes() & IMG_GIF) {
  573. if (!$this->checkImageSize($imagePath)) {
  574. return false;
  575. }
  576. $this->resource = imagecreatefromgif($imagePath);
  577. if ($this->resource) {
  578. // Preserve transparency
  579. imagealphablending($this->resource, true);
  580. imagesavealpha($this->resource, true);
  581. } else {
  582. $this->logger->debug('OC_Image->loadFromFile, GIF image not valid: ' . $imagePath, ['app' => 'core']);
  583. }
  584. } else {
  585. $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, ['app' => 'core']);
  586. }
  587. break;
  588. case IMAGETYPE_JPEG:
  589. if (imagetypes() & IMG_JPG) {
  590. if (!$this->checkImageSize($imagePath)) {
  591. return false;
  592. }
  593. if (@getimagesize($imagePath) !== false) {
  594. $this->resource = @imagecreatefromjpeg($imagePath);
  595. } else {
  596. $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, ['app' => 'core']);
  597. }
  598. } else {
  599. $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, ['app' => 'core']);
  600. }
  601. break;
  602. case IMAGETYPE_PNG:
  603. if (imagetypes() & IMG_PNG) {
  604. if (!$this->checkImageSize($imagePath)) {
  605. return false;
  606. }
  607. $this->resource = @imagecreatefrompng($imagePath);
  608. if ($this->resource) {
  609. // Preserve transparency
  610. imagealphablending($this->resource, true);
  611. imagesavealpha($this->resource, true);
  612. } else {
  613. $this->logger->debug('OC_Image->loadFromFile, PNG image not valid: ' . $imagePath, ['app' => 'core']);
  614. }
  615. } else {
  616. $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, ['app' => 'core']);
  617. }
  618. break;
  619. case IMAGETYPE_XBM:
  620. if (imagetypes() & IMG_XPM) {
  621. if (!$this->checkImageSize($imagePath)) {
  622. return false;
  623. }
  624. $this->resource = @imagecreatefromxbm($imagePath);
  625. } else {
  626. $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, ['app' => 'core']);
  627. }
  628. break;
  629. case IMAGETYPE_WBMP:
  630. if (imagetypes() & IMG_WBMP) {
  631. if (!$this->checkImageSize($imagePath)) {
  632. return false;
  633. }
  634. $this->resource = @imagecreatefromwbmp($imagePath);
  635. } else {
  636. $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, ['app' => 'core']);
  637. }
  638. break;
  639. case IMAGETYPE_BMP:
  640. $this->resource = imagecreatefrombmp($imagePath);
  641. break;
  642. case IMAGETYPE_WEBP:
  643. if (imagetypes() & IMG_WEBP) {
  644. if (!$this->checkImageSize($imagePath)) {
  645. return false;
  646. }
  647. // Check for animated header before generating preview since libgd does not handle them well
  648. // Adapted from here: https://stackoverflow.com/a/68491679/4085517 (stripped to only to check for animations + added additional error checking)
  649. // Header format details here: https://developers.google.com/speed/webp/docs/riff_container
  650. // Load up the header data, if any
  651. $fp = fopen($imagePath, 'rb');
  652. if (!$fp) {
  653. return false;
  654. }
  655. $data = fread($fp, 90);
  656. if (!$data) {
  657. return false;
  658. }
  659. fclose($fp);
  660. unset($fp);
  661. $headerFormat = 'A4Riff/' . // get n string
  662. 'I1Filesize/' . // get integer (file size but not actual size)
  663. 'A4Webp/' . // get n string
  664. 'A4Vp/' . // get n string
  665. 'A74Chunk';
  666. $header = unpack($headerFormat, $data);
  667. unset($data, $headerFormat);
  668. if (!$header) {
  669. return false;
  670. }
  671. // Check if we're really dealing with a valid WEBP header rather than just one suffixed ".webp"
  672. if (!isset($header['Riff']) || strtoupper($header['Riff']) !== 'RIFF') {
  673. return false;
  674. }
  675. if (!isset($header['Webp']) || strtoupper($header['Webp']) !== 'WEBP') {
  676. return false;
  677. }
  678. if (!isset($header['Vp']) || strpos(strtoupper($header['Vp']), 'VP8') === false) {
  679. return false;
  680. }
  681. // Check for animation indicators
  682. if (strpos(strtoupper($header['Chunk']), 'ANIM') !== false || strpos(strtoupper($header['Chunk']), 'ANMF') !== false) {
  683. // Animated so don't let it reach libgd
  684. $this->logger->debug('OC_Image->loadFromFile, animated WEBP images not supported: ' . $imagePath, ['app' => 'core']);
  685. } else {
  686. // We're safe so give it to libgd
  687. $this->resource = @imagecreatefromwebp($imagePath);
  688. }
  689. } else {
  690. $this->logger->debug('OC_Image->loadFromFile, WEBP images not supported: ' . $imagePath, ['app' => 'core']);
  691. }
  692. break;
  693. /*
  694. case IMAGETYPE_TIFF_II: // (intel byte order)
  695. break;
  696. case IMAGETYPE_TIFF_MM: // (motorola byte order)
  697. break;
  698. case IMAGETYPE_JPC:
  699. break;
  700. case IMAGETYPE_JP2:
  701. break;
  702. case IMAGETYPE_JPX:
  703. break;
  704. case IMAGETYPE_JB2:
  705. break;
  706. case IMAGETYPE_SWC:
  707. break;
  708. case IMAGETYPE_IFF:
  709. break;
  710. case IMAGETYPE_ICO:
  711. break;
  712. case IMAGETYPE_SWF:
  713. break;
  714. case IMAGETYPE_PSD:
  715. break;
  716. */
  717. default:
  718. // this is mostly file created from encrypted file
  719. $data = file_get_contents($imagePath);
  720. if (!$this->checkImageDataSize($data)) {
  721. return false;
  722. }
  723. $this->resource = @imagecreatefromstring($data);
  724. $iType = IMAGETYPE_PNG;
  725. $this->logger->debug('OC_Image->loadFromFile, Default', ['app' => 'core']);
  726. break;
  727. }
  728. if ($this->valid()) {
  729. $this->imageType = $iType;
  730. $this->mimeType = image_type_to_mime_type($iType);
  731. $this->filePath = $imagePath;
  732. }
  733. return $this->resource;
  734. }
  735. /**
  736. * Loads an image from a string of data.
  737. *
  738. * @param string $str A string of image data as read from a file.
  739. * @return bool|\GdImage An image resource or false on error
  740. */
  741. public function loadFromData(string $str) {
  742. if (!$this->checkImageDataSize($str)) {
  743. return false;
  744. }
  745. $this->resource = @imagecreatefromstring($str);
  746. if ($this->fileInfo) {
  747. $this->mimeType = $this->fileInfo->buffer($str);
  748. }
  749. if ($this->valid()) {
  750. imagealphablending($this->resource, false);
  751. imagesavealpha($this->resource, true);
  752. }
  753. if (!$this->resource) {
  754. $this->logger->debug('OC_Image->loadFromFile, could not load', ['app' => 'core']);
  755. return false;
  756. }
  757. return $this->resource;
  758. }
  759. /**
  760. * Loads an image from a base64 encoded string.
  761. *
  762. * @param string $str A string base64 encoded string of image data.
  763. * @return bool|\GdImage An image resource or false on error
  764. */
  765. public function loadFromBase64(string $str) {
  766. $data = base64_decode($str);
  767. if ($data) { // try to load from string data
  768. if (!$this->checkImageDataSize($data)) {
  769. return false;
  770. }
  771. $this->resource = @imagecreatefromstring($data);
  772. if ($this->fileInfo) {
  773. $this->mimeType = $this->fileInfo->buffer($data);
  774. }
  775. if (!$this->resource) {
  776. $this->logger->debug('OC_Image->loadFromBase64, could not load', ['app' => 'core']);
  777. return false;
  778. }
  779. return $this->resource;
  780. } else {
  781. return false;
  782. }
  783. }
  784. /**
  785. * Resizes the image preserving ratio.
  786. *
  787. * @param int $maxSize The maximum size of either the width or height.
  788. * @return bool
  789. */
  790. public function resize(int $maxSize): bool {
  791. if (!$this->valid()) {
  792. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  793. return false;
  794. }
  795. $result = $this->resizeNew($maxSize);
  796. imagedestroy($this->resource);
  797. $this->resource = $result;
  798. return $this->valid();
  799. }
  800. /**
  801. * @param $maxSize
  802. * @return bool|\GdImage
  803. */
  804. private function resizeNew(int $maxSize) {
  805. if (!$this->valid()) {
  806. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  807. return false;
  808. }
  809. $widthOrig = imagesx($this->resource);
  810. $heightOrig = imagesy($this->resource);
  811. $ratioOrig = $widthOrig / $heightOrig;
  812. if ($ratioOrig > 1) {
  813. $newHeight = round($maxSize / $ratioOrig);
  814. $newWidth = $maxSize;
  815. } else {
  816. $newWidth = round($maxSize * $ratioOrig);
  817. $newHeight = $maxSize;
  818. }
  819. return $this->preciseResizeNew((int)round($newWidth), (int)round($newHeight));
  820. }
  821. /**
  822. * @param int $width
  823. * @param int $height
  824. * @return bool
  825. */
  826. public function preciseResize(int $width, int $height): bool {
  827. if (!$this->valid()) {
  828. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  829. return false;
  830. }
  831. $result = $this->preciseResizeNew($width, $height);
  832. imagedestroy($this->resource);
  833. $this->resource = $result;
  834. return $this->valid();
  835. }
  836. /**
  837. * @param int $width
  838. * @param int $height
  839. * @return bool|\GdImage
  840. */
  841. public function preciseResizeNew(int $width, int $height) {
  842. if (!($width > 0) || !($height > 0)) {
  843. $this->logger->info(__METHOD__ . '(): Requested image size not bigger than 0', ['app' => 'core']);
  844. return false;
  845. }
  846. if (!$this->valid()) {
  847. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  848. return false;
  849. }
  850. $widthOrig = imagesx($this->resource);
  851. $heightOrig = imagesy($this->resource);
  852. $process = imagecreatetruecolor($width, $height);
  853. if ($process === false) {
  854. $this->logger->debug(__METHOD__ . '(): Error creating true color image', ['app' => 'core']);
  855. return false;
  856. }
  857. // preserve transparency
  858. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  859. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  860. imagealphablending($process, false);
  861. imagesavealpha($process, true);
  862. }
  863. $res = imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
  864. if ($res === false) {
  865. $this->logger->debug(__METHOD__ . '(): Error re-sampling process image', ['app' => 'core']);
  866. imagedestroy($process);
  867. return false;
  868. }
  869. return $process;
  870. }
  871. /**
  872. * Crops the image to the middle square. If the image is already square it just returns.
  873. *
  874. * @param int $size maximum size for the result (optional)
  875. * @return bool for success or failure
  876. */
  877. public function centerCrop(int $size = 0): bool {
  878. if (!$this->valid()) {
  879. $this->logger->debug('OC_Image->centerCrop, No image loaded', ['app' => 'core']);
  880. return false;
  881. }
  882. $widthOrig = imagesx($this->resource);
  883. $heightOrig = imagesy($this->resource);
  884. if ($widthOrig === $heightOrig and $size == 0) {
  885. return true;
  886. }
  887. $ratioOrig = $widthOrig / $heightOrig;
  888. $width = $height = min($widthOrig, $heightOrig);
  889. if ($ratioOrig > 1) {
  890. $x = (int) (($widthOrig / 2) - ($width / 2));
  891. $y = 0;
  892. } else {
  893. $y = (int) (($heightOrig / 2) - ($height / 2));
  894. $x = 0;
  895. }
  896. if ($size > 0) {
  897. $targetWidth = $size;
  898. $targetHeight = $size;
  899. } else {
  900. $targetWidth = $width;
  901. $targetHeight = $height;
  902. }
  903. $process = imagecreatetruecolor($targetWidth, $targetHeight);
  904. if ($process === false) {
  905. $this->logger->debug('OC_Image->centerCrop, Error creating true color image', ['app' => 'core']);
  906. return false;
  907. }
  908. // preserve transparency
  909. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  910. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127) ?: null);
  911. imagealphablending($process, false);
  912. imagesavealpha($process, true);
  913. }
  914. $result = imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
  915. if ($result === false) {
  916. $this->logger->debug('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, ['app' => 'core']);
  917. return false;
  918. }
  919. imagedestroy($this->resource);
  920. $this->resource = $process;
  921. return true;
  922. }
  923. /**
  924. * Crops the image from point $x$y with dimension $wx$h.
  925. *
  926. * @param int $x Horizontal position
  927. * @param int $y Vertical position
  928. * @param int $w Width
  929. * @param int $h Height
  930. * @return bool for success or failure
  931. */
  932. public function crop(int $x, int $y, int $w, int $h): bool {
  933. if (!$this->valid()) {
  934. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  935. return false;
  936. }
  937. $result = $this->cropNew($x, $y, $w, $h);
  938. imagedestroy($this->resource);
  939. $this->resource = $result;
  940. return $this->valid();
  941. }
  942. /**
  943. * Crops the image from point $x$y with dimension $wx$h.
  944. *
  945. * @param int $x Horizontal position
  946. * @param int $y Vertical position
  947. * @param int $w Width
  948. * @param int $h Height
  949. * @return \GdImage|false
  950. */
  951. public function cropNew(int $x, int $y, int $w, int $h) {
  952. if (!$this->valid()) {
  953. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  954. return false;
  955. }
  956. $process = imagecreatetruecolor($w, $h);
  957. if ($process === false) {
  958. $this->logger->debug(__METHOD__ . '(): Error creating true color image', ['app' => 'core']);
  959. return false;
  960. }
  961. // preserve transparency
  962. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  963. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127) ?: null);
  964. imagealphablending($process, false);
  965. imagesavealpha($process, true);
  966. }
  967. $result = imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
  968. if ($result === false) {
  969. $this->logger->debug(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, ['app' => 'core']);
  970. return false;
  971. }
  972. return $process;
  973. }
  974. /**
  975. * Resizes the image to fit within a boundary while preserving ratio.
  976. *
  977. * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
  978. *
  979. * @param int $maxWidth
  980. * @param int $maxHeight
  981. * @return bool
  982. */
  983. public function fitIn(int $maxWidth, int $maxHeight): bool {
  984. if (!$this->valid()) {
  985. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  986. return false;
  987. }
  988. $widthOrig = imagesx($this->resource);
  989. $heightOrig = imagesy($this->resource);
  990. $ratio = $widthOrig / $heightOrig;
  991. $newWidth = min($maxWidth, $ratio * $maxHeight);
  992. $newHeight = min($maxHeight, $maxWidth / $ratio);
  993. $this->preciseResize((int)round($newWidth), (int)round($newHeight));
  994. return true;
  995. }
  996. /**
  997. * Shrinks larger images to fit within specified boundaries while preserving ratio.
  998. *
  999. * @param int $maxWidth
  1000. * @param int $maxHeight
  1001. * @return bool
  1002. */
  1003. public function scaleDownToFit(int $maxWidth, int $maxHeight): bool {
  1004. if (!$this->valid()) {
  1005. $this->logger->debug(__METHOD__ . '(): No image loaded', ['app' => 'core']);
  1006. return false;
  1007. }
  1008. $widthOrig = imagesx($this->resource);
  1009. $heightOrig = imagesy($this->resource);
  1010. if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
  1011. return $this->fitIn($maxWidth, $maxHeight);
  1012. }
  1013. return false;
  1014. }
  1015. public function copy(): IImage {
  1016. $image = new OC_Image(null, $this->logger, $this->config);
  1017. $image->resource = imagecreatetruecolor($this->width(), $this->height());
  1018. imagecopy(
  1019. $image->resource(),
  1020. $this->resource(),
  1021. 0,
  1022. 0,
  1023. 0,
  1024. 0,
  1025. $this->width(),
  1026. $this->height()
  1027. );
  1028. return $image;
  1029. }
  1030. public function cropCopy(int $x, int $y, int $w, int $h): IImage {
  1031. $image = new OC_Image(null, $this->logger, $this->config);
  1032. $image->imageType = $this->imageType;
  1033. $image->mimeType = $this->mimeType;
  1034. $image->resource = $this->cropNew($x, $y, $w, $h);
  1035. return $image;
  1036. }
  1037. public function preciseResizeCopy(int $width, int $height): IImage {
  1038. $image = new OC_Image(null, $this->logger, $this->config);
  1039. $image->imageType = $this->imageType;
  1040. $image->mimeType = $this->mimeType;
  1041. $image->resource = $this->preciseResizeNew($width, $height);
  1042. return $image;
  1043. }
  1044. public function resizeCopy(int $maxSize): IImage {
  1045. $image = new OC_Image(null, $this->logger, $this->config);
  1046. $image->imageType = $this->imageType;
  1047. $image->mimeType = $this->mimeType;
  1048. $image->resource = $this->resizeNew($maxSize);
  1049. return $image;
  1050. }
  1051. /**
  1052. * Destroys the current image and resets the object
  1053. */
  1054. public function destroy(): void {
  1055. if ($this->valid()) {
  1056. imagedestroy($this->resource);
  1057. }
  1058. $this->resource = false;
  1059. }
  1060. public function __destruct() {
  1061. $this->destroy();
  1062. }
  1063. }
  1064. if (!function_exists('exif_imagetype')) {
  1065. /**
  1066. * Workaround if exif_imagetype does not exist
  1067. *
  1068. * @link https://www.php.net/manual/en/function.exif-imagetype.php#80383
  1069. * @param string $fileName
  1070. * @return int|false
  1071. */
  1072. function exif_imagetype(string $fileName) {
  1073. if (($info = getimagesize($fileName)) !== false) {
  1074. return $info[2];
  1075. }
  1076. return false;
  1077. }
  1078. }