image.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bartek Przybylski <bart.p.pl@gmail.com>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Byron Marohn <combustible@live.com>
  10. * @author Christopher Schäpers <kondou@ts.unde.re>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author j-ed <juergen@eisfair.org>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Johannes Willnecker <johannes@willnecker.com>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Olivier Paroz <github@oparoz.com>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Thomas Tanghus <thomas@tanghus.net>
  24. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. /**
  42. * Class for basic image manipulation
  43. */
  44. class OC_Image implements \OCP\IImage {
  45. /** @var false|resource */
  46. protected $resource = false; // tmp resource.
  47. /** @var int */
  48. protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
  49. /** @var string */
  50. protected $mimeType = 'image/png'; // Default to png
  51. /** @var int */
  52. protected $bitDepth = 24;
  53. /** @var null|string */
  54. protected $filePath = null;
  55. /** @var finfo */
  56. private $fileInfo;
  57. /** @var \OCP\ILogger */
  58. private $logger;
  59. /** @var \OCP\IConfig */
  60. private $config;
  61. /** @var array */
  62. private $exif;
  63. /**
  64. * Constructor.
  65. *
  66. * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
  67. * an imagecreate* function.
  68. * @param \OCP\ILogger $logger
  69. * @param \OCP\IConfig $config
  70. * @throws \InvalidArgumentException in case the $imageRef parameter is not null
  71. */
  72. public function __construct($imageRef = null, \OCP\ILogger $logger = null, \OCP\IConfig $config = null) {
  73. $this->logger = $logger;
  74. if ($logger === null) {
  75. $this->logger = \OC::$server->getLogger();
  76. }
  77. $this->config = $config;
  78. if ($config === null) {
  79. $this->config = \OC::$server->getConfig();
  80. }
  81. if (\OC_Util::fileInfoLoaded()) {
  82. $this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
  83. }
  84. if ($imageRef !== null) {
  85. 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.');
  86. }
  87. }
  88. /**
  89. * Determine whether the object contains an image resource.
  90. *
  91. * @return bool
  92. */
  93. public function valid() { // apparently you can't name a method 'empty'...
  94. return is_resource($this->resource);
  95. }
  96. /**
  97. * Returns the MIME type of the image or an empty string if no image is loaded.
  98. *
  99. * @return string
  100. */
  101. public function mimeType() {
  102. return $this->valid() ? $this->mimeType : '';
  103. }
  104. /**
  105. * Returns the width of the image or -1 if no image is loaded.
  106. *
  107. * @return int
  108. */
  109. public function width() {
  110. return $this->valid() ? imagesx($this->resource) : -1;
  111. }
  112. /**
  113. * Returns the height of the image or -1 if no image is loaded.
  114. *
  115. * @return int
  116. */
  117. public function height() {
  118. return $this->valid() ? imagesy($this->resource) : -1;
  119. }
  120. /**
  121. * Returns the width when the image orientation is top-left.
  122. *
  123. * @return int
  124. */
  125. public function widthTopLeft() {
  126. $o = $this->getOrientation();
  127. $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
  128. switch ($o) {
  129. case -1:
  130. case 1:
  131. case 2: // Not tested
  132. case 3:
  133. case 4: // Not tested
  134. return $this->width();
  135. case 5: // Not tested
  136. case 6:
  137. case 7: // Not tested
  138. case 8:
  139. return $this->height();
  140. }
  141. return $this->width();
  142. }
  143. /**
  144. * Returns the height when the image orientation is top-left.
  145. *
  146. * @return int
  147. */
  148. public function heightTopLeft() {
  149. $o = $this->getOrientation();
  150. $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
  151. switch ($o) {
  152. case -1:
  153. case 1:
  154. case 2: // Not tested
  155. case 3:
  156. case 4: // Not tested
  157. return $this->height();
  158. case 5: // Not tested
  159. case 6:
  160. case 7: // Not tested
  161. case 8:
  162. return $this->width();
  163. }
  164. return $this->height();
  165. }
  166. /**
  167. * Outputs the image.
  168. *
  169. * @param string $mimeType
  170. * @return bool
  171. */
  172. public function show($mimeType = null) {
  173. if ($mimeType === null) {
  174. $mimeType = $this->mimeType();
  175. }
  176. header('Content-Type: ' . $mimeType);
  177. return $this->_output(null, $mimeType);
  178. }
  179. /**
  180. * Saves the image.
  181. *
  182. * @param string $filePath
  183. * @param string $mimeType
  184. * @return bool
  185. */
  186. public function save($filePath = null, $mimeType = null) {
  187. if ($mimeType === null) {
  188. $mimeType = $this->mimeType();
  189. }
  190. if ($filePath === null) {
  191. if ($this->filePath === null) {
  192. $this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
  193. return false;
  194. } else {
  195. $filePath = $this->filePath;
  196. }
  197. }
  198. return $this->_output($filePath, $mimeType);
  199. }
  200. /**
  201. * Outputs/saves the image.
  202. *
  203. * @param string $filePath
  204. * @param string $mimeType
  205. * @return bool
  206. * @throws Exception
  207. */
  208. private function _output($filePath = null, $mimeType = null) {
  209. if ($filePath) {
  210. if (!file_exists(dirname($filePath))) {
  211. mkdir(dirname($filePath), 0777, true);
  212. }
  213. $isWritable = is_writable(dirname($filePath));
  214. if (!$isWritable) {
  215. $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
  216. return false;
  217. } elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
  218. $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
  219. return false;
  220. }
  221. }
  222. if (!$this->valid()) {
  223. return false;
  224. }
  225. $imageType = $this->imageType;
  226. if ($mimeType !== null) {
  227. switch ($mimeType) {
  228. case 'image/gif':
  229. $imageType = IMAGETYPE_GIF;
  230. break;
  231. case 'image/jpeg':
  232. $imageType = IMAGETYPE_JPEG;
  233. break;
  234. case 'image/png':
  235. $imageType = IMAGETYPE_PNG;
  236. break;
  237. case 'image/x-xbitmap':
  238. $imageType = IMAGETYPE_XBM;
  239. break;
  240. case 'image/bmp':
  241. case 'image/x-ms-bmp':
  242. $imageType = IMAGETYPE_BMP;
  243. break;
  244. default:
  245. throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
  246. }
  247. }
  248. switch ($imageType) {
  249. case IMAGETYPE_GIF:
  250. $retVal = imagegif($this->resource, $filePath);
  251. break;
  252. case IMAGETYPE_JPEG:
  253. $retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());
  254. break;
  255. case IMAGETYPE_PNG:
  256. $retVal = imagepng($this->resource, $filePath);
  257. break;
  258. case IMAGETYPE_XBM:
  259. if (function_exists('imagexbm')) {
  260. $retVal = imagexbm($this->resource, $filePath);
  261. } else {
  262. throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
  263. }
  264. break;
  265. case IMAGETYPE_WBMP:
  266. $retVal = imagewbmp($this->resource, $filePath);
  267. break;
  268. case IMAGETYPE_BMP:
  269. $retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
  270. break;
  271. default:
  272. $retVal = imagepng($this->resource, $filePath);
  273. }
  274. return $retVal;
  275. }
  276. /**
  277. * Prints the image when called as $image().
  278. */
  279. public function __invoke() {
  280. return $this->show();
  281. }
  282. /**
  283. * @param resource Returns the image resource in any.
  284. * @throws \InvalidArgumentException in case the supplied resource does not have the type "gd"
  285. */
  286. public function setResource($resource) {
  287. if (get_resource_type($resource) === 'gd') {
  288. $this->resource = $resource;
  289. return;
  290. }
  291. throw new \InvalidArgumentException('Supplied resource is not of type "gd".');
  292. }
  293. /**
  294. * @return resource Returns the image resource in any.
  295. */
  296. public function resource() {
  297. return $this->resource;
  298. }
  299. /**
  300. * @return string Returns the mimetype of the data. Returns the empty string
  301. * if the data is not valid.
  302. */
  303. public function dataMimeType() {
  304. if (!$this->valid()) {
  305. return '';
  306. }
  307. switch ($this->mimeType) {
  308. case 'image/png':
  309. case 'image/jpeg':
  310. case 'image/gif':
  311. return $this->mimeType;
  312. default:
  313. return 'image/png';
  314. }
  315. }
  316. /**
  317. * @return null|string Returns the raw image data.
  318. */
  319. public function data() {
  320. if (!$this->valid()) {
  321. return null;
  322. }
  323. ob_start();
  324. switch ($this->mimeType) {
  325. case "image/png":
  326. $res = imagepng($this->resource);
  327. break;
  328. case "image/jpeg":
  329. $quality = $this->getJpegQuality();
  330. if ($quality !== null) {
  331. $res = imagejpeg($this->resource, null, $quality);
  332. } else {
  333. $res = imagejpeg($this->resource);
  334. }
  335. break;
  336. case "image/gif":
  337. $res = imagegif($this->resource);
  338. break;
  339. default:
  340. $res = imagepng($this->resource);
  341. $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
  342. break;
  343. }
  344. if (!$res) {
  345. $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
  346. }
  347. return ob_get_clean();
  348. }
  349. /**
  350. * @return string - base64 encoded, which is suitable for embedding in a VCard.
  351. */
  352. public function __toString() {
  353. return base64_encode($this->data());
  354. }
  355. /**
  356. * @return int|null
  357. */
  358. protected function getJpegQuality() {
  359. $quality = $this->config->getAppValue('preview', 'jpeg_quality', 90);
  360. if ($quality !== null) {
  361. $quality = min(100, max(10, (int) $quality));
  362. }
  363. return $quality;
  364. }
  365. /**
  366. * (I'm open for suggestions on better method name ;)
  367. * Get the orientation based on EXIF data.
  368. *
  369. * @return int The orientation or -1 if no EXIF data is available.
  370. */
  371. public function getOrientation() {
  372. if ($this->exif !== null) {
  373. return $this->exif['Orientation'];
  374. }
  375. if ($this->imageType !== IMAGETYPE_JPEG) {
  376. $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
  377. return -1;
  378. }
  379. if (!is_callable('exif_read_data')) {
  380. $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
  381. return -1;
  382. }
  383. if (!$this->valid()) {
  384. $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
  385. return -1;
  386. }
  387. if (is_null($this->filePath) || !is_readable($this->filePath)) {
  388. $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
  389. return -1;
  390. }
  391. $exif = @exif_read_data($this->filePath, 'IFD0');
  392. if (!$exif) {
  393. return -1;
  394. }
  395. if (!isset($exif['Orientation'])) {
  396. return -1;
  397. }
  398. $this->exif = $exif;
  399. return $exif['Orientation'];
  400. }
  401. public function readExif($data) {
  402. if (!is_callable('exif_read_data')) {
  403. $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
  404. return;
  405. }
  406. if (!$this->valid()) {
  407. $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
  408. return;
  409. }
  410. $exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
  411. if (!$exif) {
  412. return;
  413. }
  414. if (!isset($exif['Orientation'])) {
  415. return;
  416. }
  417. $this->exif = $exif;
  418. }
  419. /**
  420. * (I'm open for suggestions on better method name ;)
  421. * Fixes orientation based on EXIF data.
  422. *
  423. * @return bool
  424. */
  425. public function fixOrientation() {
  426. $o = $this->getOrientation();
  427. $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('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', array('app' => 'core'));
  475. return false;
  476. }
  477. } else {
  478. $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
  479. return false;
  480. }
  481. } else {
  482. $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('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 resource|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. * Loads an image from a local file.
  504. *
  505. * @param bool|string $imagePath The path to a local file.
  506. * @return bool|resource An image resource or false on error
  507. */
  508. public function loadFromFile($imagePath = false) {
  509. // exif_imagetype throws "read error!" if file is less than 12 byte
  510. if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
  511. return false;
  512. }
  513. $iType = exif_imagetype($imagePath);
  514. switch ($iType) {
  515. case IMAGETYPE_GIF:
  516. if (imagetypes() & IMG_GIF) {
  517. $this->resource = imagecreatefromgif($imagePath);
  518. // Preserve transparency
  519. imagealphablending($this->resource, true);
  520. imagesavealpha($this->resource, true);
  521. } else {
  522. $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
  523. }
  524. break;
  525. case IMAGETYPE_JPEG:
  526. if (imagetypes() & IMG_JPG) {
  527. if (getimagesize($imagePath) !== false) {
  528. $this->resource = @imagecreatefromjpeg($imagePath);
  529. } else {
  530. $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
  531. }
  532. } else {
  533. $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
  534. }
  535. break;
  536. case IMAGETYPE_PNG:
  537. if (imagetypes() & IMG_PNG) {
  538. $this->resource = @imagecreatefrompng($imagePath);
  539. // Preserve transparency
  540. imagealphablending($this->resource, true);
  541. imagesavealpha($this->resource, true);
  542. } else {
  543. $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
  544. }
  545. break;
  546. case IMAGETYPE_XBM:
  547. if (imagetypes() & IMG_XPM) {
  548. $this->resource = @imagecreatefromxbm($imagePath);
  549. } else {
  550. $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
  551. }
  552. break;
  553. case IMAGETYPE_WBMP:
  554. if (imagetypes() & IMG_WBMP) {
  555. $this->resource = @imagecreatefromwbmp($imagePath);
  556. } else {
  557. $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
  558. }
  559. break;
  560. case IMAGETYPE_BMP:
  561. $this->resource = $this->imagecreatefrombmp($imagePath);
  562. break;
  563. /*
  564. case IMAGETYPE_TIFF_II: // (intel byte order)
  565. break;
  566. case IMAGETYPE_TIFF_MM: // (motorola byte order)
  567. break;
  568. case IMAGETYPE_JPC:
  569. break;
  570. case IMAGETYPE_JP2:
  571. break;
  572. case IMAGETYPE_JPX:
  573. break;
  574. case IMAGETYPE_JB2:
  575. break;
  576. case IMAGETYPE_SWC:
  577. break;
  578. case IMAGETYPE_IFF:
  579. break;
  580. case IMAGETYPE_ICO:
  581. break;
  582. case IMAGETYPE_SWF:
  583. break;
  584. case IMAGETYPE_PSD:
  585. break;
  586. */
  587. default:
  588. // this is mostly file created from encrypted file
  589. $this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
  590. $iType = IMAGETYPE_PNG;
  591. $this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
  592. break;
  593. }
  594. if ($this->valid()) {
  595. $this->imageType = $iType;
  596. $this->mimeType = image_type_to_mime_type($iType);
  597. $this->filePath = $imagePath;
  598. }
  599. return $this->resource;
  600. }
  601. /**
  602. * Loads an image from a string of data.
  603. *
  604. * @param string $str A string of image data as read from a file.
  605. * @return bool|resource An image resource or false on error
  606. */
  607. public function loadFromData($str) {
  608. if (is_resource($str)) {
  609. return false;
  610. }
  611. $this->resource = @imagecreatefromstring($str);
  612. if ($this->fileInfo) {
  613. $this->mimeType = $this->fileInfo->buffer($str);
  614. }
  615. if (is_resource($this->resource)) {
  616. imagealphablending($this->resource, false);
  617. imagesavealpha($this->resource, true);
  618. }
  619. if (!$this->resource) {
  620. $this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
  621. return false;
  622. }
  623. return $this->resource;
  624. }
  625. /**
  626. * Loads an image from a base64 encoded string.
  627. *
  628. * @param string $str A string base64 encoded string of image data.
  629. * @return bool|resource An image resource or false on error
  630. */
  631. public function loadFromBase64($str) {
  632. if (!is_string($str)) {
  633. return false;
  634. }
  635. $data = base64_decode($str);
  636. if ($data) { // try to load from string data
  637. $this->resource = @imagecreatefromstring($data);
  638. if ($this->fileInfo) {
  639. $this->mimeType = $this->fileInfo->buffer($data);
  640. }
  641. if (!$this->resource) {
  642. $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
  643. return false;
  644. }
  645. return $this->resource;
  646. } else {
  647. return false;
  648. }
  649. }
  650. /**
  651. * Create a new image from file or URL
  652. *
  653. * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
  654. * @version 1.00
  655. * @param string $fileName <p>
  656. * Path to the BMP image.
  657. * </p>
  658. * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
  659. */
  660. private function imagecreatefrombmp($fileName) {
  661. if (!($fh = fopen($fileName, 'rb'))) {
  662. $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
  663. return false;
  664. }
  665. // read file header
  666. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  667. // check for bitmap
  668. if ($meta['type'] != 19778) {
  669. fclose($fh);
  670. $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
  671. return false;
  672. }
  673. // read image header
  674. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  675. // read additional 16bit header
  676. if ($meta['bits'] == 16) {
  677. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  678. }
  679. // set bytes and padding
  680. $meta['bytes'] = $meta['bits'] / 8;
  681. $this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
  682. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
  683. if ($meta['decal'] == 4) {
  684. $meta['decal'] = 0;
  685. }
  686. // obtain imagesize
  687. if ($meta['imagesize'] < 1) {
  688. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  689. // in rare cases filesize is equal to offset so we need to read physical size
  690. if ($meta['imagesize'] < 1) {
  691. $meta['imagesize'] = @filesize($fileName) - $meta['offset'];
  692. if ($meta['imagesize'] < 1) {
  693. fclose($fh);
  694. $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
  695. return false;
  696. }
  697. }
  698. }
  699. // calculate colors
  700. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  701. // read color palette
  702. $palette = array();
  703. if ($meta['bits'] < 16) {
  704. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  705. // in rare cases the color value is signed
  706. if ($palette[1] < 0) {
  707. foreach ($palette as $i => $color) {
  708. $palette[$i] = $color + 16777216;
  709. }
  710. }
  711. }
  712. // create gd image
  713. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  714. if ($im == false) {
  715. fclose($fh);
  716. $this->logger->warning(
  717. 'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
  718. array('app' => 'core'));
  719. return false;
  720. }
  721. $data = fread($fh, $meta['imagesize']);
  722. $p = 0;
  723. $vide = chr(0);
  724. $y = $meta['height'] - 1;
  725. $error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
  726. // loop through the image data beginning with the lower left corner
  727. while ($y >= 0) {
  728. $x = 0;
  729. while ($x < $meta['width']) {
  730. switch ($meta['bits']) {
  731. case 32:
  732. case 24:
  733. if (!($part = substr($data, $p, 3))) {
  734. $this->logger->warning($error, array('app' => 'core'));
  735. return $im;
  736. }
  737. $color = @unpack('V', $part . $vide);
  738. break;
  739. case 16:
  740. if (!($part = substr($data, $p, 2))) {
  741. fclose($fh);
  742. $this->logger->warning($error, array('app' => 'core'));
  743. return $im;
  744. }
  745. $color = @unpack('v', $part);
  746. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
  747. break;
  748. case 8:
  749. $color = @unpack('n', $vide . ($data[$p] ?? ''));
  750. $color[1] = isset($palette[$color[1] + 1]) ? $palette[$color[1] + 1] : $palette[1];
  751. break;
  752. case 4:
  753. $color = @unpack('n', $vide . ($data[floor($p)] ?? ''));
  754. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  755. $color[1] = isset($palette[$color[1] + 1]) ? $palette[$color[1] + 1] : $palette[1];
  756. break;
  757. case 1:
  758. $color = @unpack('n', $vide . ($data[floor($p)] ?? ''));
  759. switch (($p * 8) % 8) {
  760. case 0:
  761. $color[1] = $color[1] >> 7;
  762. break;
  763. case 1:
  764. $color[1] = ($color[1] & 0x40) >> 6;
  765. break;
  766. case 2:
  767. $color[1] = ($color[1] & 0x20) >> 5;
  768. break;
  769. case 3:
  770. $color[1] = ($color[1] & 0x10) >> 4;
  771. break;
  772. case 4:
  773. $color[1] = ($color[1] & 0x8) >> 3;
  774. break;
  775. case 5:
  776. $color[1] = ($color[1] & 0x4) >> 2;
  777. break;
  778. case 6:
  779. $color[1] = ($color[1] & 0x2) >> 1;
  780. break;
  781. case 7:
  782. $color[1] = ($color[1] & 0x1);
  783. break;
  784. }
  785. $color[1] = isset($palette[$color[1] + 1]) ? $palette[$color[1] + 1] : $palette[1];
  786. break;
  787. default:
  788. fclose($fh);
  789. $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
  790. return false;
  791. }
  792. imagesetpixel($im, $x, $y, $color[1]);
  793. $x++;
  794. $p += $meta['bytes'];
  795. }
  796. $y--;
  797. $p += $meta['decal'];
  798. }
  799. fclose($fh);
  800. return $im;
  801. }
  802. /**
  803. * Resizes the image preserving ratio.
  804. *
  805. * @param integer $maxSize The maximum size of either the width or height.
  806. * @return bool
  807. */
  808. public function resize($maxSize) {
  809. if (!$this->valid()) {
  810. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  811. return false;
  812. }
  813. $widthOrig = imagesx($this->resource);
  814. $heightOrig = imagesy($this->resource);
  815. $ratioOrig = $widthOrig / $heightOrig;
  816. if ($ratioOrig > 1) {
  817. $newHeight = round($maxSize / $ratioOrig);
  818. $newWidth = $maxSize;
  819. } else {
  820. $newWidth = round($maxSize * $ratioOrig);
  821. $newHeight = $maxSize;
  822. }
  823. $this->preciseResize((int)round($newWidth), (int)round($newHeight));
  824. return true;
  825. }
  826. /**
  827. * @param int $width
  828. * @param int $height
  829. * @return bool
  830. */
  831. public function preciseResize(int $width, int $height): bool {
  832. if (!$this->valid()) {
  833. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  834. return false;
  835. }
  836. $widthOrig = imagesx($this->resource);
  837. $heightOrig = imagesy($this->resource);
  838. $process = imagecreatetruecolor($width, $height);
  839. if ($process == false) {
  840. $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
  841. imagedestroy($process);
  842. return false;
  843. }
  844. // preserve transparency
  845. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  846. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  847. imagealphablending($process, false);
  848. imagesavealpha($process, true);
  849. }
  850. imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
  851. if ($process == false) {
  852. $this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
  853. imagedestroy($process);
  854. return false;
  855. }
  856. imagedestroy($this->resource);
  857. $this->resource = $process;
  858. return true;
  859. }
  860. /**
  861. * Crops the image to the middle square. If the image is already square it just returns.
  862. *
  863. * @param int $size maximum size for the result (optional)
  864. * @return bool for success or failure
  865. */
  866. public function centerCrop($size = 0) {
  867. if (!$this->valid()) {
  868. $this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
  869. return false;
  870. }
  871. $widthOrig = imagesx($this->resource);
  872. $heightOrig = imagesy($this->resource);
  873. if ($widthOrig === $heightOrig and $size == 0) {
  874. return true;
  875. }
  876. $ratioOrig = $widthOrig / $heightOrig;
  877. $width = $height = min($widthOrig, $heightOrig);
  878. if ($ratioOrig > 1) {
  879. $x = ($widthOrig / 2) - ($width / 2);
  880. $y = 0;
  881. } else {
  882. $y = ($heightOrig / 2) - ($height / 2);
  883. $x = 0;
  884. }
  885. if ($size > 0) {
  886. $targetWidth = $size;
  887. $targetHeight = $size;
  888. } else {
  889. $targetWidth = $width;
  890. $targetHeight = $height;
  891. }
  892. $process = imagecreatetruecolor($targetWidth, $targetHeight);
  893. if ($process == false) {
  894. $this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
  895. imagedestroy($process);
  896. return false;
  897. }
  898. // preserve transparency
  899. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  900. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  901. imagealphablending($process, false);
  902. imagesavealpha($process, true);
  903. }
  904. imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
  905. if ($process == false) {
  906. $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
  907. imagedestroy($process);
  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->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  926. return false;
  927. }
  928. $process = imagecreatetruecolor($w, $h);
  929. if ($process == false) {
  930. $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
  931. imagedestroy($process);
  932. return false;
  933. }
  934. // preserve transparency
  935. if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
  936. imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
  937. imagealphablending($process, false);
  938. imagesavealpha($process, true);
  939. }
  940. imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
  941. if ($process == false) {
  942. $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
  943. imagedestroy($process);
  944. return false;
  945. }
  946. imagedestroy($this->resource);
  947. $this->resource = $process;
  948. return true;
  949. }
  950. /**
  951. * Resizes the image to fit within a boundary while preserving ratio.
  952. *
  953. * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
  954. *
  955. * @param integer $maxWidth
  956. * @param integer $maxHeight
  957. * @return bool
  958. */
  959. public function fitIn($maxWidth, $maxHeight) {
  960. if (!$this->valid()) {
  961. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  962. return false;
  963. }
  964. $widthOrig = imagesx($this->resource);
  965. $heightOrig = imagesy($this->resource);
  966. $ratio = $widthOrig / $heightOrig;
  967. $newWidth = min($maxWidth, $ratio * $maxHeight);
  968. $newHeight = min($maxHeight, $maxWidth / $ratio);
  969. $this->preciseResize((int)round($newWidth), (int)round($newHeight));
  970. return true;
  971. }
  972. /**
  973. * Shrinks larger images to fit within specified boundaries while preserving ratio.
  974. *
  975. * @param integer $maxWidth
  976. * @param integer $maxHeight
  977. * @return bool
  978. */
  979. public function scaleDownToFit($maxWidth, $maxHeight) {
  980. if (!$this->valid()) {
  981. $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
  982. return false;
  983. }
  984. $widthOrig = imagesx($this->resource);
  985. $heightOrig = imagesy($this->resource);
  986. if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
  987. return $this->fitIn($maxWidth, $maxHeight);
  988. }
  989. return false;
  990. }
  991. /**
  992. * Destroys the current image and resets the object
  993. */
  994. public function destroy() {
  995. if ($this->valid()) {
  996. imagedestroy($this->resource);
  997. }
  998. $this->resource = null;
  999. }
  1000. public function __destruct() {
  1001. $this->destroy();
  1002. }
  1003. }
  1004. if (!function_exists('imagebmp')) {
  1005. /**
  1006. * Output a BMP image to either the browser or a file
  1007. *
  1008. * @link http://www.ugia.cn/wp-data/imagebmp.php
  1009. * @author legend <legendsky@hotmail.com>
  1010. * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
  1011. * @author mgutt <marc@gutt.it>
  1012. * @version 1.00
  1013. * @param resource $im
  1014. * @param string $fileName [optional] <p>The path to save the file to.</p>
  1015. * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
  1016. * @param int $compression [optional]
  1017. * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
  1018. */
  1019. function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
  1020. if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
  1021. $bit = 24;
  1022. } else if ($bit == 32) {
  1023. $bit = 24;
  1024. }
  1025. $bits = pow(2, $bit);
  1026. imagetruecolortopalette($im, true, $bits);
  1027. $width = imagesx($im);
  1028. $height = imagesy($im);
  1029. $colorsNum = imagecolorstotal($im);
  1030. $rgbQuad = '';
  1031. if ($bit <= 8) {
  1032. for ($i = 0; $i < $colorsNum; $i++) {
  1033. $colors = imagecolorsforindex($im, $i);
  1034. $rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
  1035. }
  1036. $bmpData = '';
  1037. if ($compression == 0 || $bit < 8) {
  1038. $compression = 0;
  1039. $extra = '';
  1040. $padding = 4 - ceil($width / (8 / $bit)) % 4;
  1041. if ($padding % 4 != 0) {
  1042. $extra = str_repeat("\0", $padding);
  1043. }
  1044. for ($j = $height - 1; $j >= 0; $j--) {
  1045. $i = 0;
  1046. while ($i < $width) {
  1047. $bin = 0;
  1048. $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
  1049. for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
  1050. $index = imagecolorat($im, $i, $j);
  1051. $bin |= $index << $k;
  1052. $i++;
  1053. }
  1054. $bmpData .= chr($bin);
  1055. }
  1056. $bmpData .= $extra;
  1057. }
  1058. } // RLE8
  1059. else if ($compression == 1 && $bit == 8) {
  1060. for ($j = $height - 1; $j >= 0; $j--) {
  1061. $lastIndex = "\0";
  1062. $sameNum = 0;
  1063. for ($i = 0; $i <= $width; $i++) {
  1064. $index = imagecolorat($im, $i, $j);
  1065. if ($index !== $lastIndex || $sameNum > 255) {
  1066. if ($sameNum != 0) {
  1067. $bmpData .= chr($sameNum) . chr($lastIndex);
  1068. }
  1069. $lastIndex = $index;
  1070. $sameNum = 1;
  1071. } else {
  1072. $sameNum++;
  1073. }
  1074. }
  1075. $bmpData .= "\0\0";
  1076. }
  1077. $bmpData .= "\0\1";
  1078. }
  1079. $sizeQuad = strlen($rgbQuad);
  1080. $sizeData = strlen($bmpData);
  1081. } else {
  1082. $extra = '';
  1083. $padding = 4 - ($width * ($bit / 8)) % 4;
  1084. if ($padding % 4 != 0) {
  1085. $extra = str_repeat("\0", $padding);
  1086. }
  1087. $bmpData = '';
  1088. for ($j = $height - 1; $j >= 0; $j--) {
  1089. for ($i = 0; $i < $width; $i++) {
  1090. $index = imagecolorat($im, $i, $j);
  1091. $colors = imagecolorsforindex($im, $index);
  1092. if ($bit == 16) {
  1093. $bin = 0 << $bit;
  1094. $bin |= ($colors['red'] >> 3) << 10;
  1095. $bin |= ($colors['green'] >> 3) << 5;
  1096. $bin |= $colors['blue'] >> 3;
  1097. $bmpData .= pack("v", $bin);
  1098. } else {
  1099. $bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
  1100. }
  1101. }
  1102. $bmpData .= $extra;
  1103. }
  1104. $sizeQuad = 0;
  1105. $sizeData = strlen($bmpData);
  1106. $colorsNum = 0;
  1107. }
  1108. $fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
  1109. $infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
  1110. if ($fileName != '') {
  1111. $fp = fopen($fileName, 'wb');
  1112. fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
  1113. fclose($fp);
  1114. return true;
  1115. }
  1116. echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
  1117. return true;
  1118. }
  1119. }
  1120. if (!function_exists('exif_imagetype')) {
  1121. /**
  1122. * Workaround if exif_imagetype does not exist
  1123. *
  1124. * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
  1125. * @param string $fileName
  1126. * @return string|boolean
  1127. */
  1128. function exif_imagetype($fileName) {
  1129. if (($info = getimagesize($fileName)) !== false) {
  1130. return $info[2];
  1131. }
  1132. return false;
  1133. }
  1134. }