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