OC_Image.php 31 KB

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