1
0

OC_Image.php 31 KB

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