imagefile.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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)) {
  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->id);
  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 ServerException(sprintf('Image not available locally: %s', $imgPath));
  134. }
  135. try {
  136. $image = new ImageFile($file->id, $imgPath);
  137. } catch (UnsupportedMediaException $e) {
  138. // Avoid deleting the original
  139. if ($imgPath != $file->getPath()) {
  140. unlink($imgPath);
  141. }
  142. throw $e;
  143. }
  144. return $image;
  145. }
  146. public function getPath()
  147. {
  148. if (!file_exists($this->filepath)) {
  149. throw new FileNotFoundException($this->filepath);
  150. }
  151. return $this->filepath;
  152. }
  153. static function fromUpload($param='upload')
  154. {
  155. switch ($_FILES[$param]['error']) {
  156. case UPLOAD_ERR_OK: // success, jump out
  157. break;
  158. case UPLOAD_ERR_INI_SIZE:
  159. case UPLOAD_ERR_FORM_SIZE:
  160. // TRANS: Exception thrown when too large a file is uploaded.
  161. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  162. throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
  163. case UPLOAD_ERR_PARTIAL:
  164. @unlink($_FILES[$param]['tmp_name']);
  165. // TRANS: Exception thrown when uploading an image and that action could not be completed.
  166. throw new Exception(_('Partial upload.'));
  167. case UPLOAD_ERR_NO_FILE:
  168. // No file; probably just a non-AJAX submission.
  169. default:
  170. common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
  171. // TRANS: Exception thrown when uploading an image fails for an unknown reason.
  172. throw new Exception(_('System error uploading file.'));
  173. }
  174. $info = @getimagesize($_FILES[$param]['tmp_name']);
  175. if (!$info) {
  176. @unlink($_FILES[$param]['tmp_name']);
  177. // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
  178. throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
  179. }
  180. return new ImageFile(null, $_FILES[$param]['tmp_name']);
  181. }
  182. /**
  183. * Copy the image file to the given destination.
  184. *
  185. * This function may modify the resulting file. Please use the
  186. * returned ImageFile object to read metadata (width, height etc.)
  187. *
  188. * @param string $outpath
  189. * @return ImageFile the image stored at target path
  190. */
  191. function copyTo($outpath)
  192. {
  193. return new ImageFile(null, $this->resizeTo($outpath));
  194. }
  195. /**
  196. * Create and save a thumbnail image.
  197. *
  198. * @param string $outpath
  199. * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
  200. * @return string full local filesystem filename
  201. */
  202. function resizeTo($outpath, array $box=array())
  203. {
  204. $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
  205. $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
  206. $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
  207. $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
  208. $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
  209. $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
  210. if (!file_exists($this->filepath)) {
  211. // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
  212. throw new Exception(_('Lost our file.'));
  213. }
  214. // Don't rotate/crop/scale if it isn't necessary
  215. if ($box['width'] === $this->width
  216. && $box['height'] === $this->height
  217. && $box['x'] === 0
  218. && $box['y'] === 0
  219. && $box['w'] === $this->width
  220. && $box['h'] === $this->height
  221. && $this->type == $this->preferredType()) {
  222. if ($this->rotate == 0) {
  223. // No rotational difference, just copy it as-is
  224. @copy($this->filepath, $outpath);
  225. return $outpath;
  226. } elseif (abs($this->rotate) == 90) {
  227. // Box is rotated 90 degrees in either direction,
  228. // so we have to redefine x to y and vice versa.
  229. $tmp = $box['width'];
  230. $box['width'] = $box['height'];
  231. $box['height'] = $tmp;
  232. $tmp = $box['x'];
  233. $box['x'] = $box['y'];
  234. $box['y'] = $tmp;
  235. $tmp = $box['w'];
  236. $box['w'] = $box['h'];
  237. $box['h'] = $tmp;
  238. }
  239. }
  240. if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
  241. $this->resizeToFile($outpath, $box);
  242. }
  243. if (!file_exists($outpath)) {
  244. throw new UseFileAsThumbnailException($this->id);
  245. }
  246. return $outpath;
  247. }
  248. protected function resizeToFile($outpath, array $box)
  249. {
  250. switch ($this->type) {
  251. case IMAGETYPE_GIF:
  252. $image_src = imagecreatefromgif($this->filepath);
  253. break;
  254. case IMAGETYPE_JPEG:
  255. $image_src = imagecreatefromjpeg($this->filepath);
  256. break;
  257. case IMAGETYPE_PNG:
  258. $image_src = imagecreatefrompng($this->filepath);
  259. break;
  260. case IMAGETYPE_BMP:
  261. $image_src = imagecreatefrombmp($this->filepath);
  262. break;
  263. case IMAGETYPE_WBMP:
  264. $image_src = imagecreatefromwbmp($this->filepath);
  265. break;
  266. case IMAGETYPE_XBM:
  267. $image_src = imagecreatefromxbm($this->filepath);
  268. break;
  269. default:
  270. // TRANS: Exception thrown when trying to resize an unknown file type.
  271. throw new Exception(_('Unknown file type'));
  272. }
  273. if ($this->rotate != 0) {
  274. $image_src = imagerotate($image_src, $this->rotate, 0);
  275. }
  276. $image_dest = imagecreatetruecolor($box['width'], $box['height']);
  277. if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
  278. $transparent_idx = imagecolortransparent($image_src);
  279. if ($transparent_idx >= 0) {
  280. $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
  281. $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  282. imagefill($image_dest, 0, 0, $transparent_idx);
  283. imagecolortransparent($image_dest, $transparent_idx);
  284. } elseif ($this->type == IMAGETYPE_PNG) {
  285. imagealphablending($image_dest, false);
  286. $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
  287. imagefill($image_dest, 0, 0, $transparent);
  288. imagesavealpha($image_dest, true);
  289. }
  290. }
  291. imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], $box['width'], $box['height'], $box['w'], $box['h']);
  292. switch ($this->preferredType()) {
  293. case IMAGETYPE_GIF:
  294. imagegif($image_dest, $outpath);
  295. break;
  296. case IMAGETYPE_JPEG:
  297. imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
  298. break;
  299. case IMAGETYPE_PNG:
  300. imagepng($image_dest, $outpath);
  301. break;
  302. default:
  303. // TRANS: Exception thrown when trying resize an unknown file type.
  304. throw new Exception(_('Unknown file type'));
  305. }
  306. imagedestroy($image_src);
  307. imagedestroy($image_dest);
  308. }
  309. /**
  310. * Several obscure file types should be normalized to PNG on resize.
  311. *
  312. * @fixme consider flattening anything not GIF or JPEG to PNG
  313. * @return int
  314. */
  315. function preferredType()
  316. {
  317. if($this->type == IMAGETYPE_BMP) {
  318. //we don't want to save BMP... it's an inefficient, rare, antiquated format
  319. //save png instead
  320. return IMAGETYPE_PNG;
  321. } else if($this->type == IMAGETYPE_WBMP) {
  322. //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
  323. //save png instead
  324. return IMAGETYPE_PNG;
  325. } else if($this->type == IMAGETYPE_XBM) {
  326. //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
  327. //save png instead
  328. return IMAGETYPE_PNG;
  329. }
  330. return $this->type;
  331. }
  332. function unlink()
  333. {
  334. @unlink($this->filepath);
  335. }
  336. static function maxFileSize()
  337. {
  338. $value = ImageFile::maxFileSizeInt();
  339. if ($value > 1024 * 1024) {
  340. $value = $value/(1024*1024);
  341. // TRANS: Number of megabytes. %d is the number.
  342. return sprintf(_m('%dMB','%dMB',$value),$value);
  343. } else if ($value > 1024) {
  344. $value = $value/1024;
  345. // TRANS: Number of kilobytes. %d is the number.
  346. return sprintf(_m('%dkB','%dkB',$value),$value);
  347. } else {
  348. // TRANS: Number of bytes. %d is the number.
  349. return sprintf(_m('%dB','%dB',$value),$value);
  350. }
  351. }
  352. static function maxFileSizeInt()
  353. {
  354. return min(ImageFile::strToInt(ini_get('post_max_size')),
  355. ImageFile::strToInt(ini_get('upload_max_filesize')),
  356. ImageFile::strToInt(ini_get('memory_limit')));
  357. }
  358. static function strToInt($str)
  359. {
  360. $unit = substr($str, -1);
  361. $num = substr($str, 0, -1);
  362. switch(strtoupper($unit)){
  363. case 'G':
  364. $num *= 1024;
  365. case 'M':
  366. $num *= 1024;
  367. case 'K':
  368. $num *= 1024;
  369. }
  370. return $num;
  371. }
  372. public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
  373. {
  374. return self::getScalingValues($this->width, $this->height,
  375. $maxWidth, $maxHeight, $crop, $this->rotate);
  376. }
  377. /*
  378. * Gets scaling values for images of various types. Cropping can be enabled.
  379. *
  380. * Values will scale _up_ to fit max values if cropping is enabled!
  381. * With cropping disabled, the max value of each axis will be respected.
  382. *
  383. * @param $width int Original width
  384. * @param $height int Original height
  385. * @param $maxW int Resulting max width
  386. * @param $maxH int Resulting max height
  387. * @param $crop int Crop to the size (not preserving aspect ratio)
  388. */
  389. public static function getScalingValues($width, $height,
  390. $maxW=null, $maxH=null,
  391. $crop=null, $rotate=0)
  392. {
  393. $maxW = $maxW ?: common_config('thumbnail', 'width');
  394. $maxH = $maxH ?: common_config('thumbnail', 'height');
  395. if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
  396. throw new ServerException('Bad parameters for ImageFile::getScalingValues');
  397. } elseif ($maxH === null) {
  398. // if maxH is null, we set maxH to equal maxW and enable crop
  399. $maxH = $maxW;
  400. $crop = true;
  401. }
  402. // Because GD doesn't understand EXIF orientation etc.
  403. if (abs($rotate) == 90) {
  404. $tmp = $width;
  405. $width = $height;
  406. $height = $tmp;
  407. }
  408. // Cropping data (for original image size). Default values, 0 and null,
  409. // imply no cropping and with preserved aspect ratio (per axis).
  410. $cx = 0; // crop x
  411. $cy = 0; // crop y
  412. $cw = null; // crop area width
  413. $ch = null; // crop area height
  414. if ($crop) {
  415. $s_ar = $width / $height;
  416. $t_ar = $maxW / $maxH;
  417. $rw = $maxW;
  418. $rh = $maxH;
  419. // Source aspect ratio differs from target, recalculate crop points!
  420. if ($s_ar > $t_ar) {
  421. $cx = floor($width / 2 - $height * $t_ar / 2);
  422. $cw = ceil($height * $t_ar);
  423. } elseif ($s_ar < $t_ar) {
  424. $cy = floor($height / 2 - $width / $t_ar / 2);
  425. $ch = ceil($width / $t_ar);
  426. }
  427. } else {
  428. $rw = $maxW;
  429. $rh = ceil($height * $rw / $width);
  430. // Scaling caused too large height, decrease to max accepted value
  431. if ($rh > $maxH) {
  432. $rh = $maxH;
  433. $rw = ceil($width * $rh / $height);
  434. }
  435. }
  436. return array(intval($rw), intval($rh),
  437. intval($cx), intval($cy),
  438. is_null($cw) ? $width : intval($cw),
  439. is_null($ch) ? $height : intval($ch));
  440. }
  441. /**
  442. * Animated GIF test, courtesy of frank at huddler dot com et al:
  443. * http://php.net/manual/en/function.imagecreatefromgif.php#104473
  444. * Modified so avoid landing inside of a header (and thus not matching our regexp).
  445. */
  446. protected function isAnimatedGif()
  447. {
  448. if (!($fh = @fopen($this->filepath, 'rb'))) {
  449. return false;
  450. }
  451. $count = 0;
  452. //an animated gif contains multiple "frames", with each frame having a
  453. //header made up of:
  454. // * a static 4-byte sequence (\x00\x21\xF9\x04)
  455. // * 4 variable bytes
  456. // * a static 2-byte sequence (\x00\x2C)
  457. // In total the header is maximum 10 bytes.
  458. // We read through the file til we reach the end of the file, or we've found
  459. // at least 2 frame headers
  460. while(!feof($fh) && $count < 2) {
  461. $chunk = fread($fh, 1024 * 100); //read 100kb at a time
  462. $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
  463. // rewind in case we ended up in the middle of the header, but avoid
  464. // infinite loop (i.e. don't rewind if we're already in the end).
  465. if (!feof($fh) && ftell($fh) >= 9) {
  466. fseek($fh, -9, SEEK_CUR);
  467. }
  468. }
  469. fclose($fh);
  470. return $count > 1;
  471. }
  472. public function getFileThumbnail($width, $height, $crop)
  473. {
  474. if (!$this->fileRecord instanceof File) {
  475. throw new ServerException('No File object attached to this ImageFile object.');
  476. }
  477. if ($width === null) {
  478. $width = common_config('thumbnail', 'width');
  479. $height = common_config('thumbnail', 'height');
  480. $crop = common_config('thumbnail', 'crop');
  481. }
  482. if ($height === null) {
  483. $height = $width;
  484. $crop = true;
  485. }
  486. // Get proper aspect ratio width and height before lookup
  487. // We have to do it through an ImageFile object because of orientation etc.
  488. // Only other solution would've been to rotate + rewrite uploaded files
  489. // which we don't want to do because we like original, untouched data!
  490. list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
  491. $thumb = File_thumbnail::pkeyGet(array(
  492. 'file_id'=> $this->fileRecord->id,
  493. 'width' => $width,
  494. 'height' => $height,
  495. ));
  496. if ($thumb instanceof File_thumbnail) {
  497. return $thumb;
  498. }
  499. $filename = $this->fileRecord->filehash ?: $this->filename; // Remote files don't have $this->filehash
  500. $extension = File::guessMimeExtension($this->mimetype);
  501. $outname = "thumb-{$this->fileRecord->id}-{$width}x{$height}-{$filename}." . $extension;
  502. $outpath = File_thumbnail::path($outname);
  503. // The boundary box for our resizing
  504. $box = array('width'=>$width, 'height'=>$height,
  505. 'x'=>$x, 'y'=>$y,
  506. 'w'=>$w, 'h'=>$h);
  507. // Doublecheck that parameters are sane and integers.
  508. if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
  509. || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
  510. || $box['w'] < 1 || $box['x'] >= $this->width
  511. || $box['h'] < 1 || $box['y'] >= $this->height) {
  512. // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
  513. common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box,true));
  514. throw new ServerException('Bad thumbnail size parameters.');
  515. }
  516. common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->fileRecord->id, $width, $height));
  517. // Perform resize and store into file
  518. $this->resizeTo($outpath, $box);
  519. // Avoid deleting the original
  520. if ($this->getPath() != File_thumbnail::path($this->filename)) {
  521. $this->unlink();
  522. }
  523. return File_thumbnail::saveThumbnail($this->fileRecord->id,
  524. File_thumbnail::url($outname),
  525. $width, $height,
  526. $outname);
  527. }
  528. }
  529. //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
  530. if(!function_exists('imagecreatefrombmp')){
  531. //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
  532. function imagecreatefrombmp($p_sFile)
  533. {
  534. // Load the image into a string
  535. $file = fopen($p_sFile,"rb");
  536. $read = fread($file,10);
  537. while(!feof($file)&&($read<>""))
  538. $read .= fread($file,1024);
  539. $temp = unpack("H*",$read);
  540. $hex = $temp[1];
  541. $header = substr($hex,0,108);
  542. // Process the header
  543. // Structure: http://www.fastgraph.com/help/bmp_header_format.html
  544. if (substr($header,0,4)=="424d")
  545. {
  546. // Cut it in parts of 2 bytes
  547. $header_parts = str_split($header,2);
  548. // Get the width 4 bytes
  549. $width = hexdec($header_parts[19].$header_parts[18]);
  550. // Get the height 4 bytes
  551. $height = hexdec($header_parts[23].$header_parts[22]);
  552. // Unset the header params
  553. unset($header_parts);
  554. }
  555. // Define starting X and Y
  556. $x = 0;
  557. $y = 1;
  558. // Create newimage
  559. $image = imagecreatetruecolor($width,$height);
  560. // Grab the body from the image
  561. $body = substr($hex,108);
  562. // Calculate if padding at the end-line is needed
  563. // Divided by two to keep overview.
  564. // 1 byte = 2 HEX-chars
  565. $body_size = (strlen($body)/2);
  566. $header_size = ($width*$height);
  567. // Use end-line padding? Only when needed
  568. $usePadding = ($body_size>($header_size*3)+4);
  569. // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
  570. // Calculate the next DWORD-position in the body
  571. for ($i=0;$i<$body_size;$i+=3)
  572. {
  573. // Calculate line-ending and padding
  574. if ($x>=$width)
  575. {
  576. // If padding needed, ignore image-padding
  577. // Shift i to the ending of the current 32-bit-block
  578. if ($usePadding)
  579. $i += $width%4;
  580. // Reset horizontal position
  581. $x = 0;
  582. // Raise the height-position (bottom-up)
  583. $y++;
  584. // Reached the image-height? Break the for-loop
  585. if ($y>$height)
  586. break;
  587. }
  588. // Calculation of the RGB-pixel (defined as BGR in image-data)
  589. // Define $i_pos as absolute position in the body
  590. $i_pos = $i*2;
  591. $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
  592. $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
  593. $b = hexdec($body[$i_pos].$body[$i_pos+1]);
  594. // Calculate and draw the pixel
  595. $color = imagecolorallocate($image,$r,$g,$b);
  596. imagesetpixel($image,$x,$height-$y,$color);
  597. // Raise the horizontal position
  598. $x++;
  599. }
  600. // Unset the body / free the memory
  601. unset($body);
  602. // Return image-object
  603. return $image;
  604. }
  605. } // if(!function_exists('imagecreatefrombmp'))