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