OC_Image.php 32 KB

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