OC_Image.php 34 KB

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