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