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