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