imagefile.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Abstraction for an image file
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category Image
  23. * @package StatusNet
  24. * @author Evan Prodromou <evan@status.net>
  25. * @author Zach Copley <zach@status.net>
  26. * @copyright 2008-2009 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('GNUSOCIAL')) { exit(1); }
  31. /**
  32. * A wrapper on uploaded files
  33. *
  34. * Makes it slightly easier to accept an image file from upload.
  35. *
  36. * @category Image
  37. * @package StatusNet
  38. * @author Evan Prodromou <evan@status.net>
  39. * @author Zach Copley <zach@status.net>
  40. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  41. * @link http://status.net/
  42. */
  43. class ImageFile
  44. {
  45. var $id;
  46. var $filepath;
  47. var $filename;
  48. var $type;
  49. var $height;
  50. var $width;
  51. var $rotate=0; // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
  52. var $animated = null; // Animated image? (has more than 1 frame). null means untested
  53. var $mimetype = null; // The _ImageFile_ mimetype, _not_ the originating File object
  54. protected $fileRecord = null;
  55. function __construct($id, $filepath)
  56. {
  57. $this->id = $id;
  58. if (!empty($this->id)) {
  59. $this->fileRecord = new File();
  60. $this->fileRecord->id = $this->id;
  61. if (!$this->fileRecord->find(true)) {
  62. // If we have set an ID, we need that ID to exist!
  63. throw new NoResultException($this->fileRecord);
  64. }
  65. }
  66. // These do not have to be the same as fileRecord->filename for example,
  67. // since we may have generated an image source file from something else!
  68. $this->filepath = $filepath;
  69. $this->filename = basename($filepath);
  70. $info = @getimagesize($this->filepath);
  71. if (!(
  72. ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
  73. ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
  74. $info[2] == IMAGETYPE_BMP ||
  75. ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
  76. ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
  77. ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
  78. // TRANS: Exception thrown when trying to upload an unsupported image file format.
  79. throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
  80. }
  81. $this->width = $info[0];
  82. $this->height = $info[1];
  83. $this->type = $info[2];
  84. $this->mimetype = $info['mime'];
  85. if ($this->type === IMAGETYPE_JPEG && function_exists('exif_read_data')) {
  86. // Orientation value to rotate thumbnails properly
  87. $exif = @exif_read_data($this->filepath);
  88. if (is_array($exif) && isset($exif['Orientation'])) {
  89. switch ((int)$exif['Orientation']) {
  90. case 1: // top is top
  91. $this->rotate = 0;
  92. break;
  93. case 3: // top is bottom
  94. $this->rotate = 180;
  95. break;
  96. case 6: // top is right
  97. $this->rotate = -90;
  98. break;
  99. case 8: // top is left
  100. $this->rotate = 90;
  101. break;
  102. }
  103. // If we ever write this back, Orientation should be set to '1'
  104. }
  105. } elseif ($this->type === IMAGETYPE_GIF) {
  106. $this->animated = $this->isAnimatedGif();
  107. }
  108. Event::handle('FillImageFileMetadata', array($this));
  109. }
  110. public static function fromFileObject(File $file)
  111. {
  112. $imgPath = null;
  113. $media = common_get_mime_media($file->mimetype);
  114. if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
  115. if (empty($file->filename) && !file_exists($imgPath)) {
  116. throw new UnsupportedMediaException(_('File without filename could not get a thumbnail source.'));
  117. }
  118. // First some mimetype specific exceptions
  119. switch ($file->mimetype) {
  120. case 'image/svg+xml':
  121. throw new UseFileAsThumbnailException($file);
  122. }
  123. // And we'll only consider it an image if it has such a media type
  124. switch ($media) {
  125. case 'image':
  126. $imgPath = $file->getPath();
  127. break;
  128. default:
  129. throw new UnsupportedMediaException(_('Unsupported media format.'), $file->getPath());
  130. }
  131. }
  132. if (!file_exists($imgPath)) {
  133. throw new FileNotFoundException($imgPath);
  134. }
  135. try {
  136. $image = new ImageFile($file->getID(), $imgPath);
  137. } catch (Exception $e) {
  138. // Avoid deleting the original
  139. try {
  140. if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
  141. common_debug(__METHOD__.': Deleting temporary file that was created as image file thumbnail source: '._ve($imgPath));
  142. @unlink($imgPath);
  143. }
  144. } catch (FileNotFoundException $e) {
  145. // File reported (via getPath) that the original file
  146. // doesn't exist anyway, so it's safe to delete $imgPath
  147. @unlink($imgPath);
  148. }
  149. common_debug(sprintf('Exception %s caught when creating ImageFile for File id==%s and imgPath==%s: %s', get_class($e), _ve($file->id), _ve($imgPath), _ve($e->getMessage())));
  150. throw $e;
  151. }
  152. return $image;
  153. }
  154. public function getPath()
  155. {
  156. if (!file_exists($this->filepath)) {
  157. throw new FileNotFoundException($this->filepath);
  158. }
  159. return $this->filepath;
  160. }
  161. static function fromUpload($param='upload')
  162. {
  163. switch ($_FILES[$param]['error']) {
  164. case UPLOAD_ERR_OK: // success, jump out
  165. break;
  166. case UPLOAD_ERR_INI_SIZE:
  167. case UPLOAD_ERR_FORM_SIZE:
  168. // TRANS: Exception thrown when too large a file is uploaded.
  169. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  170. throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
  171. case UPLOAD_ERR_PARTIAL:
  172. @unlink($_FILES[$param]['tmp_name']);
  173. // TRANS: Exception thrown when uploading an image and that action could not be completed.
  174. throw new Exception(_('Partial upload.'));
  175. case UPLOAD_ERR_NO_FILE:
  176. // No file; probably just a non-AJAX submission.
  177. throw new ClientException(_('No file uploaded.'));
  178. default:
  179. common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
  180. // TRANS: Exception thrown when uploading an image fails for an unknown reason.
  181. throw new Exception(_('System error uploading file.'));
  182. }
  183. $info = @getimagesize($_FILES[$param]['tmp_name']);
  184. if (!$info) {
  185. @unlink($_FILES[$param]['tmp_name']);
  186. // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
  187. throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
  188. }
  189. return new ImageFile(null, $_FILES[$param]['tmp_name']);
  190. }
  191. /**
  192. * Copy the image file to the given destination.
  193. *
  194. * This function may modify the resulting file. Please use the
  195. * returned ImageFile object to read metadata (width, height etc.)
  196. *
  197. * @param string $outpath
  198. * @return ImageFile the image stored at target path
  199. */
  200. function copyTo($outpath)
  201. {
  202. return new ImageFile(null, $this->resizeTo($outpath));
  203. }
  204. /**
  205. * Create and save a thumbnail image.
  206. *
  207. * @param string $outpath
  208. * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
  209. * @return string full local filesystem filename
  210. */
  211. function resizeTo($outpath, array $box=array())
  212. {
  213. $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
  214. $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
  215. $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
  216. $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
  217. $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
  218. $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
  219. if (!file_exists($this->filepath)) {
  220. // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
  221. throw new Exception(_('Lost our file.'));
  222. }
  223. // Don't rotate/crop/scale if it isn't necessary
  224. if ($box['width'] === $this->width
  225. && $box['height'] === $this->height
  226. && $box['x'] === 0
  227. && $box['y'] === 0
  228. && $box['w'] === $this->width
  229. && $box['h'] === $this->height
  230. && $this->type == $this->preferredType()) {
  231. if ($this->rotate == 0) {
  232. // No rotational difference, just copy it as-is
  233. @copy($this->filepath, $outpath);
  234. return $outpath;
  235. } elseif (abs($this->rotate) == 90) {
  236. // Box is rotated 90 degrees in either direction,
  237. // so we have to redefine x to y and vice versa.
  238. $tmp = $box['width'];
  239. $box['width'] = $box['height'];
  240. $box['height'] = $tmp;
  241. $tmp = $box['x'];
  242. $box['x'] = $box['y'];
  243. $box['y'] = $tmp;
  244. $tmp = $box['w'];
  245. $box['w'] = $box['h'];
  246. $box['h'] = $tmp;
  247. }
  248. }
  249. if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
  250. $this->resizeToFile($outpath, $box);
  251. }
  252. if (!file_exists($outpath)) {
  253. if ($this->fileRecord instanceof File) {
  254. throw new UseFileAsThumbnailException($this->fileRecord);
  255. } else {
  256. throw new UnsupportedMediaException('No local File object exists for ImageFile.');
  257. }
  258. }
  259. return $outpath;
  260. }
  261. protected function resizeToFile($outpath, array $box)
  262. {
  263. switch ($this->type) {
  264. case IMAGETYPE_GIF:
  265. $image_src = imagecreatefromgif($this->filepath);
  266. break;
  267. case IMAGETYPE_JPEG:
  268. $image_src = imagecreatefromjpeg($this->filepath);
  269. break;
  270. case IMAGETYPE_PNG:
  271. $image_src = imagecreatefrompng($this->filepath);
  272. break;
  273. case IMAGETYPE_BMP:
  274. $image_src = imagecreatefrombmp($this->filepath);
  275. break;
  276. case IMAGETYPE_WBMP:
  277. $image_src = imagecreatefromwbmp($this->filepath);
  278. break;
  279. case IMAGETYPE_XBM:
  280. $image_src = imagecreatefromxbm($this->filepath);
  281. break;
  282. default:
  283. // TRANS: Exception thrown when trying to resize an unknown file type.
  284. throw new Exception(_('Unknown file type'));
  285. }
  286. if ($this->rotate != 0) {
  287. $image_src = imagerotate($image_src, $this->rotate, 0);
  288. }
  289. $image_dest = imagecreatetruecolor($box['width'], $box['height']);
  290. if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
  291. $transparent_idx = imagecolortransparent($image_src);
  292. if ($transparent_idx >= 0) {
  293. $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
  294. $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  295. imagefill($image_dest, 0, 0, $transparent_idx);
  296. imagecolortransparent($image_dest, $transparent_idx);
  297. } elseif ($this->type == IMAGETYPE_PNG) {
  298. imagealphablending($image_dest, false);
  299. $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
  300. imagefill($image_dest, 0, 0, $transparent);
  301. imagesavealpha($image_dest, true);
  302. }
  303. }
  304. imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], $box['width'], $box['height'], $box['w'], $box['h']);
  305. switch ($this->preferredType()) {
  306. case IMAGETYPE_GIF:
  307. imagegif($image_dest, $outpath);
  308. break;
  309. case IMAGETYPE_JPEG:
  310. imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
  311. break;
  312. case IMAGETYPE_PNG:
  313. imagepng($image_dest, $outpath);
  314. break;
  315. default:
  316. // TRANS: Exception thrown when trying resize an unknown file type.
  317. throw new Exception(_('Unknown file type'));
  318. }
  319. imagedestroy($image_src);
  320. imagedestroy($image_dest);
  321. }
  322. /**
  323. * Several obscure file types should be normalized to PNG on resize.
  324. *
  325. * @fixme consider flattening anything not GIF or JPEG to PNG
  326. * @return int
  327. */
  328. function preferredType()
  329. {
  330. if($this->type == IMAGETYPE_BMP) {
  331. //we don't want to save BMP... it's an inefficient, rare, antiquated format
  332. //save png instead
  333. return IMAGETYPE_PNG;
  334. } else if($this->type == IMAGETYPE_WBMP) {
  335. //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
  336. //save png instead
  337. return IMAGETYPE_PNG;
  338. } else if($this->type == IMAGETYPE_XBM) {
  339. //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
  340. //save png instead
  341. return IMAGETYPE_PNG;
  342. }
  343. return $this->type;
  344. }
  345. function unlink()
  346. {
  347. @unlink($this->filepath);
  348. }
  349. static function maxFileSize()
  350. {
  351. $value = ImageFile::maxFileSizeInt();
  352. if ($value > 1024 * 1024) {
  353. $value = $value/(1024*1024);
  354. // TRANS: Number of megabytes. %d is the number.
  355. return sprintf(_m('%dMB','%dMB',$value),$value);
  356. } else if ($value > 1024) {
  357. $value = $value/1024;
  358. // TRANS: Number of kilobytes. %d is the number.
  359. return sprintf(_m('%dkB','%dkB',$value),$value);
  360. } else {
  361. // TRANS: Number of bytes. %d is the number.
  362. return sprintf(_m('%dB','%dB',$value),$value);
  363. }
  364. }
  365. static function maxFileSizeInt()
  366. {
  367. return min(ImageFile::strToInt(ini_get('post_max_size')),
  368. ImageFile::strToInt(ini_get('upload_max_filesize')),
  369. ImageFile::strToInt(ini_get('memory_limit')));
  370. }
  371. static function strToInt($str)
  372. {
  373. $unit = substr($str, -1);
  374. $num = substr($str, 0, -1);
  375. switch(strtoupper($unit)){
  376. case 'G':
  377. $num *= 1024;
  378. case 'M':
  379. $num *= 1024;
  380. case 'K':
  381. $num *= 1024;
  382. }
  383. return $num;
  384. }
  385. public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
  386. {
  387. return self::getScalingValues($this->width, $this->height,
  388. $maxWidth, $maxHeight, $crop, $this->rotate);
  389. }
  390. /*
  391. * Gets scaling values for images of various types. Cropping can be enabled.
  392. *
  393. * Values will scale _up_ to fit max values if cropping is enabled!
  394. * With cropping disabled, the max value of each axis will be respected.
  395. *
  396. * @param $width int Original width
  397. * @param $height int Original height
  398. * @param $maxW int Resulting max width
  399. * @param $maxH int Resulting max height
  400. * @param $crop int Crop to the size (not preserving aspect ratio)
  401. */
  402. public static function getScalingValues($width, $height,
  403. $maxW=null, $maxH=null,
  404. $crop=null, $rotate=0)
  405. {
  406. $maxW = $maxW ?: common_config('thumbnail', 'width');
  407. $maxH = $maxH ?: common_config('thumbnail', 'height');
  408. if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
  409. throw new ServerException('Bad parameters for ImageFile::getScalingValues');
  410. } elseif ($maxH === null) {
  411. // if maxH is null, we set maxH to equal maxW and enable crop
  412. $maxH = $maxW;
  413. $crop = true;
  414. }
  415. // Because GD doesn't understand EXIF orientation etc.
  416. if (abs($rotate) == 90) {
  417. $tmp = $width;
  418. $width = $height;
  419. $height = $tmp;
  420. }
  421. // Cropping data (for original image size). Default values, 0 and null,
  422. // imply no cropping and with preserved aspect ratio (per axis).
  423. $cx = 0; // crop x
  424. $cy = 0; // crop y
  425. $cw = null; // crop area width
  426. $ch = null; // crop area height
  427. if ($crop) {
  428. $s_ar = $width / $height;
  429. $t_ar = $maxW / $maxH;
  430. $rw = $maxW;
  431. $rh = $maxH;
  432. // Source aspect ratio differs from target, recalculate crop points!
  433. if ($s_ar > $t_ar) {
  434. $cx = floor($width / 2 - $height * $t_ar / 2);
  435. $cw = ceil($height * $t_ar);
  436. } elseif ($s_ar < $t_ar) {
  437. $cy = floor($height / 2 - $width / $t_ar / 2);
  438. $ch = ceil($width / $t_ar);
  439. }
  440. } else {
  441. $rw = $maxW;
  442. $rh = ceil($height * $rw / $width);
  443. // Scaling caused too large height, decrease to max accepted value
  444. if ($rh > $maxH) {
  445. $rh = $maxH;
  446. $rw = ceil($width * $rh / $height);
  447. }
  448. }
  449. return array(intval($rw), intval($rh),
  450. intval($cx), intval($cy),
  451. is_null($cw) ? $width : intval($cw),
  452. is_null($ch) ? $height : intval($ch));
  453. }
  454. /**
  455. * Animated GIF test, courtesy of frank at huddler dot com et al:
  456. * http://php.net/manual/en/function.imagecreatefromgif.php#104473
  457. * Modified so avoid landing inside of a header (and thus not matching our regexp).
  458. */
  459. protected function isAnimatedGif()
  460. {
  461. if (!($fh = @fopen($this->filepath, 'rb'))) {
  462. return false;
  463. }
  464. $count = 0;
  465. //an animated gif contains multiple "frames", with each frame having a
  466. //header made up of:
  467. // * a static 4-byte sequence (\x00\x21\xF9\x04)
  468. // * 4 variable bytes
  469. // * a static 2-byte sequence (\x00\x2C)
  470. // In total the header is maximum 10 bytes.
  471. // We read through the file til we reach the end of the file, or we've found
  472. // at least 2 frame headers
  473. while(!feof($fh) && $count < 2) {
  474. $chunk = fread($fh, 1024 * 100); //read 100kb at a time
  475. $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
  476. // rewind in case we ended up in the middle of the header, but avoid
  477. // infinite loop (i.e. don't rewind if we're already in the end).
  478. if (!feof($fh) && ftell($fh) >= 9) {
  479. fseek($fh, -9, SEEK_CUR);
  480. }
  481. }
  482. fclose($fh);
  483. return $count >= 1; // number of animated frames apart from the original image
  484. }
  485. public function getFileThumbnail($width, $height, $crop, $upscale=false)
  486. {
  487. if (!$this->fileRecord instanceof File) {
  488. throw new ServerException('No File object attached to this ImageFile object.');
  489. }
  490. if ($width === null) {
  491. $width = common_config('thumbnail', 'width');
  492. $height = common_config('thumbnail', 'height');
  493. $crop = common_config('thumbnail', 'crop');
  494. }
  495. if (!$upscale) {
  496. if ($width > $this->width) {
  497. $width = $this->width;
  498. }
  499. if (!is_null($height) && $height > $this->height) {
  500. $height = $this->height;
  501. }
  502. }
  503. if ($height === null) {
  504. $height = $width;
  505. $crop = true;
  506. }
  507. // Get proper aspect ratio width and height before lookup
  508. // We have to do it through an ImageFile object because of orientation etc.
  509. // Only other solution would've been to rotate + rewrite uploaded files
  510. // which we don't want to do because we like original, untouched data!
  511. list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
  512. $thumb = File_thumbnail::pkeyGet(array(
  513. 'file_id'=> $this->fileRecord->getID(),
  514. 'width' => $width,
  515. 'height' => $height,
  516. ));
  517. if ($thumb instanceof File_thumbnail) {
  518. return $thumb;
  519. }
  520. $filename = $this->fileRecord->filehash ?: $this->filename; // Remote files don't have $this->filehash
  521. $extension = File::guessMimeExtension($this->mimetype);
  522. $outname = "thumb-{$this->fileRecord->getID()}-{$width}x{$height}-{$filename}." . $extension;
  523. $outpath = File_thumbnail::path($outname);
  524. // The boundary box for our resizing
  525. $box = array('width'=>$width, 'height'=>$height,
  526. 'x'=>$x, 'y'=>$y,
  527. 'w'=>$w, 'h'=>$h);
  528. // Doublecheck that parameters are sane and integers.
  529. if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
  530. || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
  531. || $box['w'] < 1 || $box['x'] >= $this->width
  532. || $box['h'] < 1 || $box['y'] >= $this->height) {
  533. // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
  534. common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box,true));
  535. throw new ServerException('Bad thumbnail size parameters.');
  536. }
  537. common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->fileRecord->getID(), $width, $height));
  538. // Perform resize and store into file
  539. $this->resizeTo($outpath, $box);
  540. try {
  541. // Avoid deleting the original
  542. if (!in_array($this->getPath(), [File::path($this->filename), File_thumbnail::path($this->filename)])) {
  543. $this->unlink();
  544. }
  545. } catch (FileNotFoundException $e) {
  546. // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
  547. }
  548. return File_thumbnail::saveThumbnail($this->fileRecord->getID(),
  549. null, // no url since we generated it ourselves and can dynamically generate the url
  550. $width, $height,
  551. $outname);
  552. }
  553. }
  554. //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
  555. if(!function_exists('imagecreatefrombmp')){
  556. //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
  557. function imagecreatefrombmp($p_sFile)
  558. {
  559. // Load the image into a string
  560. $file = fopen($p_sFile,"rb");
  561. $read = fread($file,10);
  562. while(!feof($file)&&($read<>""))
  563. $read .= fread($file,1024);
  564. $temp = unpack("H*",$read);
  565. $hex = $temp[1];
  566. $header = substr($hex,0,108);
  567. // Process the header
  568. // Structure: http://www.fastgraph.com/help/bmp_header_format.html
  569. if (substr($header,0,4)=="424d")
  570. {
  571. // Cut it in parts of 2 bytes
  572. $header_parts = str_split($header,2);
  573. // Get the width 4 bytes
  574. $width = hexdec($header_parts[19].$header_parts[18]);
  575. // Get the height 4 bytes
  576. $height = hexdec($header_parts[23].$header_parts[22]);
  577. // Unset the header params
  578. unset($header_parts);
  579. }
  580. // Define starting X and Y
  581. $x = 0;
  582. $y = 1;
  583. // Create newimage
  584. $image = imagecreatetruecolor($width,$height);
  585. // Grab the body from the image
  586. $body = substr($hex,108);
  587. // Calculate if padding at the end-line is needed
  588. // Divided by two to keep overview.
  589. // 1 byte = 2 HEX-chars
  590. $body_size = (strlen($body)/2);
  591. $header_size = ($width*$height);
  592. // Use end-line padding? Only when needed
  593. $usePadding = ($body_size>($header_size*3)+4);
  594. // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
  595. // Calculate the next DWORD-position in the body
  596. for ($i=0;$i<$body_size;$i+=3)
  597. {
  598. // Calculate line-ending and padding
  599. if ($x>=$width)
  600. {
  601. // If padding needed, ignore image-padding
  602. // Shift i to the ending of the current 32-bit-block
  603. if ($usePadding)
  604. $i += $width%4;
  605. // Reset horizontal position
  606. $x = 0;
  607. // Raise the height-position (bottom-up)
  608. $y++;
  609. // Reached the image-height? Break the for-loop
  610. if ($y>$height)
  611. break;
  612. }
  613. // Calculation of the RGB-pixel (defined as BGR in image-data)
  614. // Define $i_pos as absolute position in the body
  615. $i_pos = $i*2;
  616. $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
  617. $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
  618. $b = hexdec($body[$i_pos].$body[$i_pos+1]);
  619. // Calculate and draw the pixel
  620. $color = imagecolorallocate($image,$r,$g,$b);
  621. imagesetpixel($image,$x,$height-$y,$color);
  622. // Raise the horizontal position
  623. $x++;
  624. }
  625. // Unset the body / free the memory
  626. unset($body);
  627. // Return image-object
  628. return $image;
  629. }
  630. } // if(!function_exists('imagecreatefrombmp'))