fantasia /core/classes/framework/image/image.php

Language PHP Lines 774
MD5 Hash 8de680d0aee18b2f89ef2a899592f99c Estimated Cost $25,488 (why?)
Repository https://github.com/GinoPane/fantasia.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
<?php

class Image {

    const MIME_TYPE_JPEG    = "image/jpeg";
    const MIME_TYPE_PNG     = "image/png";
    const MIME_TYPE_GIF     = "image/gif";
    const MIME_TYPE_WBMP    = "image/wbmp";
    
    const FLIP_HORIZONTAL   = "y";
    const FLIP_VERTICAL     = "x";

    const ORIENTATION_PORTRAIT  = 1;
    const ORIENTATION_LANDSCAPE = 2;
    const ORIENTATION_SQUARE    = 3;
    
    const OUTPUT_JPEG   = "jpeg";
    const OUTPUT_JPG    = "jpg";
    const OUTPUT_PNG    = "png";
    const OUTPUT_GIF    = "gif";
    
    const DEFAULT_IMAGE_QUALITY = 90;

    /**
     *
     * @var string 
     */
    private $imagePath = "";
    
    /**
     *
     * @var resource 
     */
    private $image;
    
    /**
     *
     * @var array 
     */
    private $originalInfo = array();

    /**
     * 
     * @param string $imageFile path to the image file
     * 
     * @return \Image
     * @throws Exception
     */
    public function __construct($imageFile = null) {

        if (!$imageFile){
            throw new Exception('Path to the image file required!');
        }
        
        if(!extension_loaded('gd')){
            throw new Exception('Required extension GD is not loaded!');
        }

        if (!is_readable($imageFile)){
           throw new Exception('File is not readable!'); 
        }

        if (!$this->_load($imageFile)){
          throw new Exception('Can not load image file!');  
        } else {
            return $this;
        }
    }

    public function __destruct() {
        if($this->image){
            imagedestroy($this->image);
        }
    }

    public function _load($filename) {
        $this->imagePath = $filename;

        $info = getimagesize($this->imagePath);

        if ($info) {
            switch($info['mime']) {

                case self::MIME_TYPE_GIF:
                        $this->image = imagecreatefromgif($this->imagePath);
                        break;

                case self::MIME_TYPE_JPEG:
                        $this->image = imagecreatefromjpeg($this->imagePath);
                        break;

                case self::MIME_TYPE_PNG:
                        $this->image = imagecreatefrompng($this->imagePath);
                        break;

                case self::MIME_TYPE_WBMP:
                        $this->image = imagecreatefromwbmp($this->imagePath);
                        break;

                default:
                        throw new Exception('Invalid image: ' . $this->imagePath);
                        break;

            }
            
            imagesavealpha($this->image, true);
            imagealphablending($this->image, true);

            $this->originalInfo = array(
                'image' => $this->image,
                'width' => $info[0],
                'height' => $info[1],
                'orientation' => $this->getOrientation(),
                'exif' => function_exists('exif_read_data') ? @exif_read_data($this->imagePath) : array(),
                'format' => $this->fileExt($this->imagePath),
                'mime' => $info['mime']
            );

            return true;  
        } else {
            return false;
        }
    }

    /**
     * 
     * Restores original image
     * 
     * @return \Image
     */
    public function restore()
    {
        $this->image = $this->originalInfo['image'];
        
        return $this;
    }
    /**
     * 
     * Saves image or outputs it to the browser.
     * Available oprions are: 
     * - filename - name of destination file. Outputs to the browser if no file 
     * - format - image save format. Will be set from 'filename' option if there is one
     * or from original image info
     * - quality - quality of the image from 0 to 100. Effects on 'jpg' and 'png' output
     * 
     * @param array $options
     * @return \Image
     * @throws Exception
     */
    public function save(array $options = array()) {

        $filename = "";
        $format = "";
        $quality = self::DEFAULT_IMAGE_QUALITY;
        extract($options, EXTR_IF_EXISTS | EXTR_OVERWRITE);

        if (!$format){
            if ($filename){
                $format = $this->fileExt($filename);
            } else {
                $format = $this->originalInfo['format']; 
            }
        }

        switch(strtolower($format)) {
            case self::OUTPUT_GIF: {
                $result = imagegif($this->image, $filename);
                break;
            }

            case self::OUTPUT_JPEG:
            case self::OUTPUT_JPG: {
                $quality = $this->keepWithin($quality, 0, 100);
                $result = imagejpeg($this->image, $filename, $quality);
                break;
            }                            

            case self::OUTPUT_PNG: {
                if($quality >= 10) {
                    $quality = ($quality - $quality % 10) / 10;;
                }

                $quality = $this->keepWithin($quality, 0, 9);

                $filters = null;
                if (isset($options['pngfilters'])){
                    $filters = $options['pngfilters'];
                }

                $result = imagepng($this->image, $filename, $quality, $filters);
                break;
            }                           

            default:
                throw new Exception("Unsupported format image format: '{$format}'");
        }

        if(!$result) 
            throw new Exception('Unable to save image: ' . $filename);

        return $this;
    }

    /**
     * 
     * Returns information about original image
     * 
     * @return array
     */
    public function getOriginalInfo(){
        return $this->originalInfo;
    }
    
    /**
     * 
     * Returns mime type of the image
     * 
     * @return string
     */
    public function getMimeType(){
        return $this->originalInfo['mime'];
    }

    /**
     * 
     * Get current image width
     * 
     * @return int
     */
    public function getWidth() {
        return imagesx($this->image);
    }

    /**
     * 
     * Get current image height
     * 
     * @return int
     */
    public function getHeight() {
        return imagesy($this->image);
    }

    /**
     * 
     * Get current image orientation
     * 
     * @return string
     */
    public function getOrientation() {
        if($this->getWidth() > $this->getHeight()){
            return self::ORIENTATION_LANDSCAPE;
        }                    
        if($this->getWidth() < $this->getHeight()){
            return self::ORIENTATION_PORTRAIT;
        }
        return self::ORIENTATION_SQUARE;
    }

    /**
     * 
     * @param string $direction
     * @return \Image
     */
    private function flip($direction) {
        $height = $this->getHeight();
        $width = $this->getWidth();
        $new = imagecreatetruecolor($width, $height);
        imagealphablending($new, false);
        imagesavealpha($new, true);

        switch( strtolower($direction) ) {
            case self::FLIP_VERTICAL: {
                for($y = 0; $y < $height; $y++){
                    imagecopy($new, $this->image, 0, $y, 0, $height - $y - 1, $width, 1);
                }
                break;
            }

            case self::FLIP_HORIZONTAL: {
                for($x = 0; $x < $width; $x++){
                    imagecopy($new, $this->image, $x, 0, $width - $x - 1, 0, 1, $height);
                }
                break;
            }
        }

        $this->image = $new;

        return $this;
    }
        
    public function flipHorizontal(){
        return $this->flip(self::FLIP_HORIZONTAL);
    }

    public function flipVertical(){
        return $this->flip(self::FLIP_VERTICAL);
    }
        
    /**
     * 
     * Rotates image by $angle degrees
     * 
     * @param int $angle
     * @param string $bgColor hex color value
     * @return \Image
     * @throws Exception
     */
    public function rotate($angle, $bgColor = '#000000') {
        if (function_exists('imagerotate')){
            $rgb = $this->hex2rgb($bgColor);
            $bgColor = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']);

            $new = imagerotate($this->image, ($this->keepWithin($angle, -360, 360)), $bgColor);
            imagesavealpha($new, true);
            imagealphablending($new, true);

            $this->image = $new;

            return $this;
        } else {
            throw new Exception("Image rotate function is not supported");
        }
    }

    /**
     * 
     * Uses Exif orientation tag to orient image respectively
     * 
     * @return \Image
     */
    public function autoOrient() {
        if (isset($this->original_info['exif']['Orientation'])){
            switch( $this->original_info['exif']['Orientation'] ) {
                case 1:{
                    // Do nothing
                    break;
                }

                case 2: {
                    // Flip horizontal
                    $this->flipHorizontal();
                    break;
                }

                case 3: {
                    // Rotate 180 counterclockwise
                    $this->rotate(180);
                    break;
                }

                case 4: {
                    // vertical flip
                    $this->flipVertical();
                    break;
                }

                case 5: {
                    // flip vertically and rotate 90 clockwise
                    $this->flipVertical()->rotate(-90);
                    break; 
                }

                case 6: {
                    // Rotate 90 clockwise
                    $this->rotate(-90);
                    break;
                }

                case 7: {
                    // flip horizontally and rotate 90 clockwise 
                    $this->flipHorizontal()->rotate(-90);
                    break;
                }

                case 8: {
                    // Rotate 90 counterclockwise
                    $this->rotate(90);
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * 
     * Resizes image to the specified dimensions
     * 
     * @param type $width
     * @param type $height
     * @return \Image
     */
    public function resize($width, $height, $keepAspectRatio = false) {
        $new = imagecreatetruecolor($width, $height);
        imagealphablending($new, false);
        imagesavealpha($new, true);
        
        $dstX = 0;
        $dstY = 0;
        $dstWidth = $width;
        $dstHeight = $height;
        
        if($keepAspectRatio){
            $srcAspectRatio = $this->getWidth() / $this->getHeight();
            $dstAspectRatio = $width / $height;

            if ($srcAspectRatio > $dstAspectRatio) {
                $dstHeight = $width / $srcAspectRatio;
                $dstY = round(($height - $dstHeight) / 2);
            } elseif($srcAspectRatio < $dstAspectRatio) {
                $dstWidth = $height * $srcAspectRatio;
                $dstX = round(($width - $dstWidth) / 2);
            }
        }
        
        imagecopyresampled($new, $this->image, $dstX, $dstY, 0, 0, $dstWidth, $dstHeight, $this->getWidth(), $this->getHeight());

        $this->image = $new;

        return $this;
    }

    /**
     * 
     * @param type $width
     * @return type
     */
    public function fitToWidth($width) {
        $aspectRatio = $this->getHeight() / $this->getWidth();
        $height = $width * $aspectRatio;
        return $this->resize($width, $height);
    }	

    /**
     * 
     * @param type $height
     * @return type
     */
    public function fitToHeight($height) {
        $aspectRatio = $this->getHeight() / $this->getWidth();
        $width = $height / $aspectRatio;
        return $this->resize($width, $height);
    }	

    /**
     * 
     * Best fit to specified dimensions
     * 
     * @param type $maxWidth
     * @param type $maxHeight
     * @return \Image
     */
    public function bestFit($maxWidth, $maxHeight) {
        if($this->getWidth() == $maxWidth && $this->getHeight() == $maxHeight){
            return $this;
        }

        $aspectRatio = $this->getHeight() / $this->getWidth();

        // Make width fit into new dimensions
        if( $this->getWidth() > $maxWidth ) {
                $width = $maxWidth;
                $height = $width * $aspectRatio;
        } else {
                $width = $this->getWidth();
                $height = $this->getHeight();
        }

        // Make height fit into new dimensions
        if( $height > $maxHeight ) {
                $height = $maxHeight;
                $width = $height / $aspectRatio;
        }

        return $this->resize($width, $height);
    }	

    /**
     * 
     * Crops the image
     *  
     * @param int $x1 left
     * @param int $y1 top
     * @param int $x2 right
     * @param int $y2 bottom
     * @return \Image
     */
    public function crop($x1, $y1, $x2, $y2) {
        if( $x2 < $x1 ) list($x1, $x2) = array($x2, $x1);
        if( $y2 < $y1 ) list($y1, $y2) = array($y2, $y1);
        $cropWidth = $this->keepWithin($x2 - $x1, 0, $this->getWidth() - $x1);
        $cropHeight = $this->keepWithin($y2 - $y1, 0, $this->getHeight() - $y1);

        $new = imagecreatetruecolor($cropWidth, $cropHeight);
        imagealphablending($new, false);
        imagesavealpha($new, true);
        imagecopyresampled($new, $this->image, 0, 0, $x1, $y1, $cropWidth, $cropHeight, $cropWidth, $cropHeight);

        $this->image = $new;

        return $this;
    }	

    /**
     * 
     * Crops the biggest part of the image best for $xWidth, $yWidth.
     *  
     * @param int $xWidth 
     * @param int $yWidth
     * @return \Image
     */
    public function centerCrop($xWidth, $yWidth) {
        $height = $this->getHeight();
        $width = $this->getWidth();

        $srcAspectRatio = $this->getWidth() / $this->getHeight();
        $dstAspectRatio = $xWidth / $yWidth;

        if($srcAspectRatio > $dstAspectRatio) {
            $xOffsetWidth = $height * $dstAspectRatio;
            $yOffsetHeight = $height;
            $xOffset = ($width - $xOffsetWidth) / 2;
            $yOffset = 0;
        } elseif ($srcAspectRatio <= $dstAspectRatio) {
            $xOffsetWidth = $width;
            $yOffsetHeight = $width / $dstAspectRatio;
            $xOffset = 0;
            $yOffset = ($height - $yOffsetHeight) / 2;
        }

        $this->crop($xOffset, $yOffset, $xOffset + $xOffsetWidth, $yOffset + $yOffsetHeight);

        $this->resize($xWidth, $yWidth);

        return $this;
    }

    /**
     * 
     * Grayscale the image
     * 
     * @return \Image
     */
    public function grayscale() {
        imagefilter($this->image, IMG_FILTER_GRAYSCALE);
        return $this;
    }

    /**
     * 
     * Negate the image
     * 
     * @return \Image
     */
    public function negate() {
            imagefilter($this->image, IMG_FILTER_NEGATE);
            return $this;
    }

    /**
     * 
     * Changes brightness level
     * 
     * @param int $level
     * @return \Image
     */
    public function brightness($level) {
        imagefilter($this->image, IMG_FILTER_BRIGHTNESS, $this->keepWithin($level, -255, 255));
        return $this;
    }

    /**
     * 
     * Changes contrast level
     * 
     * @param int $level
     * @return \Image
     */
    public function contrast($level) {
        imagefilter($this->image, IMG_FILTER_CONTRAST, $this->keepWithin($level, -100, 100));
        return $this;
    }

    /**
     * 
     * Colorizes
     * 
     * @param string $color hex color 
     * @param float $opacity 0 to 1 value
     * @return \Image
     */
    public function colorize($color, $opacity = 0) {
        $rgb = $this->hex2rgb($color);
        $alpha = $this->keepWithin(127 - (127 * $opacity), 0, 127);
        imagefilter($this->image, IMG_FILTER_COLORIZE, $this->keepWithin($rgb['r'], 0, 255), $this->keepWithin($rgb['g'], 0, 255), $this->keepWithin($rgb['b'], 0, 255), $alpha);
        return $this;
    }

    /**
     * 
     * Uses edge detection to highlight the edges in the image
     * 
     * @return \Image
     */
    public function edges() {
        imagefilter($this->image, IMG_FILTER_EDGEDETECT);
        return $this;
    }

    /**
     * 
     * Embosses the image
     * 
     * @return \Image
     */
    public function emboss() {
        imagefilter($this->image, IMG_FILTER_EMBOSS);
        return $this;
    }

    /**
     * 
     * Uses mean removal to achieve a "sketchy" effect
     * 
     * @return \Image
     */
    public function meanRemove() {
        imagefilter($this->image, IMG_FILTER_MEAN_REMOVAL);
        return $this;
    }

    /**
     * 
     * Alias of meanRemove()
     * 
     * @return type
     */
    public function sketch(){
        return $this->meanRemove();
    }

    /**
     * Blurs the image using the Gaussian method
     * 
     * @param int $passes
     * @return \Image
     */
    public function gaussianBlur($passes = 1){
        for($i = 0; $i < $passes; $i++){
            imagefilter($this->image, IMG_FILTER_GAUSSIAN_BLUR);
        }

        return $this;
    }

    /**
     * Blurs the image
     * 
     * @param int $passes
     * @return \Image
     */
    public function selectiveBlur($passes = 1){
        for($i = 0; $i < $passes; $i++){
            imagefilter($this->image, IMG_FILTER_SELECTIVE_BLUR);
        }

        return $this;
    }

    /**
     * 
     * Makes the image smoother
     * 
     * @param type $level
     * @return \Image
     */
    public function smooth($level) {
        imagefilter($this->image, IMG_FILTER_SMOOTH, $this->keepWithin($level, -10, 10));
        return $this;
    }

    /**
     * 
     * Applies pixelation effect to the image
     * 
     * @param type $blockSize
     * @return \Image
     */
    public function pixelate($blockSize = 10) {
        imagefilter($this->image, IMG_FILTER_PIXELATE, $blockSize, true);
        return $this;
    }

    /**
     * 
     * Makes sepia effect
     * 
     * @return \Image
     */
    public function sepia() {
        imagefilter($this->image, IMG_FILTER_GRAYSCALE);
        $this->colorize('#704214');
        return $this;
    }

    /**
     * 
     * Ensure that the value is always between $min and $max
     * 
     * @param mixed $value
     * @param mixed $min
     * @param mixed $max
     * @return mixed
     */
    private function keepWithin($value, $min, $max) {
        if( $value < $min ) return $min;
        if( $value > $max ) return $max;
        return $value;
    }

    /**
     * 
     * Returns file extension
     * 
     * @param string $filename
     * @return string
     */
    private function fileExt($filename) {
        if(!preg_match('/\./', $filename)) {
            return '';
        }
        return preg_replace('/^.*\./', '', $filename);
    }

    /**
     * 
     * Converts hex color to its RGB representation
     * 
     * @param type $hex_color
     * @return boolean
     */
    private function hex2rgb($hex_color) {

        if($hex_color[0] == '#'){
            $hex_color = substr($hex_color, 1);
        }

        if(strlen($hex_color) == 6) {
            list($r, $g, $b) = array(
                    $hex_color[0] . $hex_color[1],
                    $hex_color[2] . $hex_color[3],
                    $hex_color[4] . $hex_color[5]
            );
        } elseif(strlen($hex_color) == 3) {
            list($r, $g, $b) = array(
                    $hex_color[0] . $hex_color[0],
                    $hex_color[1] . $hex_color[1],
                    $hex_color[2] . $hex_color[2]
            );
        } else {
            trigger_error("Hex color format is incorrect", E_USER_WARNING);
            return false;
        }

        return array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
    }
}
Back to Top