imagefile.php 26 KB

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