1
0

image.php 34 KB

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