OC_Image.php 30 KB

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