summaryrefslogtreecommitdiffstats
path: root/src/driver/gd.php
blob: c4770cea11713f55508e7c6fd499d9e5dc2539bb (plain)
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
<?php
/**
 * File containing the ezcGraphDriverGD class
 *
 * @package Graph
 * @version //autogentag//
 * @copyright Copyright (C) 2005, 2006 eZ systems as. All rights reserved.
 * @license http://ez.no/licenses/new_bsd New BSD License
 */
/**
 * Extension of the basic Driver package to utilize the GDlib.
 *
 * @package Graph
 */
class ezcGraphGdDriver extends ezcGraphDriver
{

    /**
     * Image ressource
     * 
     * @var ressource
     */
    protected $image;

    /**
     * Array with image files to draw
     * 
     * @var array
     */
    protected $preProcessImages = array();

    /**
     * List of strings to draw
     * array ( array(
     *          'text' => array( 'strings' ),
     *          'options' => ezcGraphFontOptions,
     *      )
     * 
     * @var array
     */
    protected $strings = array();

    public function __construct( array $options = array() )
    {
        $this->options = new ezcGraphGdDriverOptions( $options );
    }

    protected function getImage()
    {
        if ( !isset( $this->image ) )
        {
            $this->image = imagecreatetruecolor( 
                $this->supersample( $this->options->width ), 
                $this->supersample( $this->options->height )
            );

            // Default to a transparent white background
            $bgColor = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
            imagealphablending( $this->image, true );
            imagesavealpha( $this->image, true );
            imagefill( $this->image, 1, 1, $bgColor );

            imagesetthickness( 
                $this->image, 
                $this->options->supersampling
            );
        }

        return $this->image;
    }

    protected function allocate( ezcGraphColor $color )
    {
        $image = $this->getImage();

        if ( $color->alpha > 0 )
        {
            $fetched = imagecolorexactalpha( $image, $color->red, $color->green, $color->blue, $color->alpha / 2 );
            if ( $fetched < 0 )
            {
                $fetched = imagecolorallocatealpha( $image, $color->red, $color->green, $color->blue, $color->alpha / 2 );
            }
            return $fetched;
        }
        else
        {
            $fetched = imagecolorexact( $image, $color->red, $color->green, $color->blue );
            if ( $fetched < 0 )
            {
                $fetched = imagecolorallocate( $image, $color->red, $color->green, $color->blue );
            }
            return $fetched;
        }
    }

    protected function imageCreateFrom( $file )
    {
        $data = getimagesize( $file );

        switch ( $data[2] )
        {
            case 1:
                return array(
                    'width' => $data[0],
                    'height' => $data[1],
                    'image' => imagecreatefromgif( $file )
                );
            case 2:
                return array(
                    'width' => $data[0],
                    'height' => $data[1],
                    'image' => imagecreatefromjpeg( $file )
                );
            case 3:
                return array(
                    'width' => $data[0],
                    'height' => $data[1],
                    'image' => imagecreatefrompng( $file )
                );
            default:
                throw new ezcGraphGdDriverUnsupportedImageTypeException( $data[2] );
        }
    }

    protected function supersample( $value )
    {
        $mod = (int) floor( $this->options->supersampling / 2 );
        return $value * $this->options->supersampling - $mod;
    }

    /**
     * Draws a single polygon 
     * 
     * @param mixed $points 
     * @param ezcGraphColor $color 
     * @param mixed $filled 
     * @return void
     */
    public function drawPolygon( array $points, ezcGraphColor $color, $filled = true, $thickness = 1 )
    {
        $image = $this->getImage();

        $drawColor = $this->allocate( $color );

        // Create point array
        $pointCount = count( $points );
        $pointArray = array();
        for ( $i = 0; $i < $pointCount; ++$i )
        {
            $pointArray[] = $this->supersample( $points[$i]->x );
            $pointArray[] = $this->supersample( $points[$i]->y );
        }

        // Draw polygon
        if ( $filled )
        {
            imagefilledpolygon( $image, $pointArray, $pointCount, $drawColor );
        }
        else
        {
            imagepolygon( $image, $pointArray, $pointCount, $drawColor );
        }
    }
    
    /**
     * Draws a single line
     * 
     * @param ezcGraphCoordinate $start 
     * @param ezcGraphCoordinate $end 
     * @param ezcGraphColor $color 
     * @return void
     */
    public function drawLine( ezcGraphCoordinate $start, ezcGraphCoordinate $end, ezcGraphColor $color, $thickness = 1 )
    {
        $image = $this->getImage();

        $drawColor = $this->allocate( $color );

        imagesetthickness( 
            $this->image, 
            $this->options->supersampling * $thickness
        );

        imageline( 
            $image, 
            $this->supersample( $start->x ), 
            $this->supersample( $start->y ), 
            $this->supersample( $end->x ), 
            $this->supersample( $end->y ), 
            $drawColor
        );

        imagesetthickness( 
            $this->image, 
            $this->options->supersampling
        );
    }
    
    protected function testFitStringInTextBox( $string, ezcGraphCoordinate $position, $width, $height, $size )
    {
        // Tokenize String
        $tokens = preg_split( '/\s+/', $string );
        
        $lines = array( array() );
        $line = 0;
        foreach ( $tokens as $token )
        {
            // Add token to tested line
            $selectedLine = $lines[$line];
            $selectedLine[] = $token;

            $boundings = imagettfbbox( $size, 0, $this->options->font->path, implode( ' ', $selectedLine ) );

            // Check if line is too long
            if ( $boundings[2] > $width )
            {
                if ( count( $selectedLine ) == 1 )
                {
                    // Return false if one single word does not fit into one line
                    return false;
                }
                else
                {
                    // Put word in next line instead and reduce available height by used space
                    $lines[++$line][] = $token;
                    $height -= $size * ( 1 + $this->options->lineSpacing );
                }
            }
            else
            {
                // Everything is ok - put token in this line
                $lines[$line][] = $token;
            }
            
            // Return false if text exceeds vertical limit
            if ( $size > $height )
            {
                return false;
            }
        }

        // Check width of last line
        $boundings = imagettfbbox( $size, 0, $this->options->font->path, implode( ' ', $lines[$line] ) );
        if ( $boundings[2] > $width ) {
            return false;
        }

        // It seems to fit - return line array
        return $lines;
    }

    /**
     * Wrties text in a box of desired size
     * 
     * @param mixed $string 
     * @param ezcGraphCoordinate $position 
     * @param mixed $width 
     * @param mixed $height 
     * @param ezcGraphColor $color 
     * @return void
     */
    public function drawTextBox( $string, ezcGraphCoordinate $position, $width, $height, $align )
    {
        // Test font
        // @TODO: try to find font at standard locations if no path was provided
        if ( !is_file( $this->options->font->path ) || !is_readable( $this->options->font->path ) )
        {
            throw new ezcGraphGdDriverInvalidFontException( $this->options->font->path );
        }

        // Try to get a font size for the text to fit into the box
        $maxSize = min( $height, $this->options->font->maxFontSize );
        $result = false;
        for ( $size = $maxSize; $size >= $this->options->font->minFontSize; --$size )
        {
            $result = $this->testFitStringInTextBox( $string, $position, $width, $height, $size );
            if ( $result !== false )
            {
                break;
            }
        }

        if ( is_array( $result ) )
        {
            $this->options->font->minimalUsedFont = $size;

            $this->strings[] = array(
                'text' => $result,
                'position' => $position,
                'width' => $width,
                'height' => $height,
                'align' => $align,
                'options' => $this->options->font,
            );
        }
        else
        {
            // @TODO: Try to fit text in box with minimum font size
        }
    }
    
    protected function drawAllTexts()
    {
        $image = $this->getImage();

        foreach ( $this->strings as $text )
        {
            $size = $text['options']->minimalUsedFont;
            $font = $text['options']->path;
            $drawColor = $this->allocate( $text['options']->color );

            $completeHeight = count( $text['text'] ) * $size + ( count( $text['text'] ) - 1 ) * $this->options->lineSpacing;

            // Calculate y offset for vertical alignement
            switch ( true )
            {
                case ( $text['align'] & ezcGraph::BOTTOM ):
                    $yOffset = $text['height'] - $completeHeight;
                    break;
                case ( $text['align'] & ezcGraph::MIDDLE ):
                    $yOffset = ( $text['height'] - $completeHeight ) / 2;
                    break;
                case ( $text['align'] & ezcGraph::TOP ):
                default:
                    $yOffset = 0;
                    break;
            }

            // Render text with evaluated font size
            foreach ( $text['text'] as $line )
            {
                $string = implode( ' ', $line );
                $boundings = imagettfbbox( $size, 0, $font, $string );
                $text['position']->y += $size;

                switch ( true )
                {
                    case ( $text['align'] & ezcGraph::LEFT ):
                        imagettftext( 
                            $image, 
                            $size, 
                            0, 
                            $text['position']->x, 
                            $text['position']->y + $yOffset, 
                            $drawColor, 
                            $font, 
                            $string
                        );
                        break;
                    case ( $text['align'] & ezcGraph::RIGHT ):
                        imagettftext( 
                            $image, 
                            $size, 
                            0, 
                            $text['position']->x + ( $text['width'] - $boundings[2] ), 
                            $text['position']->y + $yOffset, 
                            $drawColor, 
                            $font, 
                            $string 
                        );
                        break;
                    case ( $text['align'] & ezcGraph::CENTER ):
                        imagettftext( 
                            $image, 
                            $size, 
                            0, 
                            $text['position']->x + ( ( $text['width'] - $boundings[2] ) / 2 ), 
                            $text['position']->y + $yOffset, 
                            $drawColor, 
                            $font, 
                            $string
                        );
                        break;
                }

                $text['position']->y += $size * $this->options->lineSpacing;
            }
        }
    }

    /**
     * Draws a sector of cirlce
     * 
     * @param ezcGraphCoordinate $center 
     * @param mixed $width
     * @param mixed $height
     * @param mixed $startAngle 
     * @param mixed $endAngle 
     * @param ezcGraphColor $color 
     * @return void
     */
    public function drawCircleSector( ezcGraphCoordinate $center, $width, $height, $startAngle, $endAngle, ezcGraphColor $color, $filled = true )
    {
        $image = $this->getImage();
        $drawColor = $this->allocate( $color );

        // Normalize angles
        if ( $startAngle > $endAngle )
        {
            $tmp = $startAngle;
            $startAngle = $endAngle;
            $endAngle = $tmp;
        }

        if ( $filled )
        {
            imagefilledarc( 
                $image, 
                $this->supersample( $center->x ), 
                $this->supersample( $center->y ), 
                $this->supersample( $width ), 
                $this->supersample( $height ), 
                $startAngle, 
                $endAngle, 
                $drawColor, 
                IMG_ARC_PIE 
            );
        }
        else
        {
            imagefilledarc( 
                $image, 
                $this->supersample( $center->x ), 
                $this->supersample( $center->y ), 
                $this->supersample( $width ), 
                $this->supersample( $height ), 
                $startAngle, 
                $endAngle, 
                $drawColor, 
                IMG_ARC_PIE | IMG_ARC_NOFILL | IMG_ARC_EDGED
            );
        }
    }

    /**
     * Draws a single element of a circular arc
     * 
     * @param ezcGraphCoordinate $center Center of ellipse
     * @param integer $width Width of ellipse
     * @param integer $height Height of ellipse
     * @param integer $size Height of border
     * @param float $startAngle Starting angle of circle sector
     * @param float $endAngle Ending angle of circle sector
     * @param ezcGraphColor $color Color of Border
     * @return void
     */
    protected function drawCircularArcStep( ezcGraphCoordinate $center, $width, $height, $size, $startAngle, $endAngle, ezcGraphColor $color )
    {
        $this->drawPolygon(
            array(
                new ezcGraphCoordinate(
                    $center->x + 
                        ( ( cos( deg2rad( $startAngle ) ) * $width ) / 2 ),
                    $center->y + 
                        ( ( sin( deg2rad( $startAngle ) ) * $height ) / 2 )
                ),
                new ezcGraphCoordinate(
                    $center->x + 
                        ( ( cos( deg2rad( $startAngle ) ) * $width ) / 2 ),
                    $center->y + 
                        ( ( sin( deg2rad( $startAngle ) ) * $height ) / 2 ) + $size
                ),
                new ezcGraphCoordinate(
                    $center->x + 
                        ( ( cos( deg2rad( $endAngle ) ) * $width ) / 2 ),
                    $center->y + 
                        ( ( sin( deg2rad( $endAngle ) ) * $height ) / 2 ) + $size
                ),
                new ezcGraphCoordinate(
                    $center->x + 
                        ( ( cos( deg2rad( $endAngle ) ) * $width ) / 2 ),
                    $center->y + 
                        ( ( sin( deg2rad( $endAngle ) ) * $height ) / 2 )
                ),
            ),
            $color->darken( $this->options->shadeCircularArc * ( 1 + cos ( deg2rad( $startAngle ) ) ) / 2 ),
            true
        );
    }
 
    /**
     * Draws a circular arc
     * 
     * @param ezcGraphCoordinate $center Center of ellipse
     * @param integer $width Width of ellipse
     * @param integer $height Height of ellipse
     * @param integer $size Height of border
     * @param float $startAngle Starting angle of circle sector
     * @param float $endAngle Ending angle of circle sector
     * @param ezcGraphColor $color Color of Border
     * @return void
     */
    public function drawCircularArc( ezcGraphCoordinate $center, $width, $height, $size, $startAngle, $endAngle, ezcGraphColor $color, $filled = true )
    {
        $image = $this->getImage();
        $drawColor = $this->allocate( $color );

        // Normalize angles
        if ( $startAngle > $endAngle )
        {
            $tmp = $startAngle;
            $startAngle = $endAngle;
            $endAngle = $tmp;
        }
 
        if ( $filled === true )
        {
            $startIteration = ceil( $startAngle / $this->options->detail ) * $this->options->detail;
            $endIteration = floor( $endAngle / $this->options->detail ) * $this->options->detail;

            if ( $startAngle < $startIteration )
            {
                // Draw initial step
                $this->drawCircularArcStep( 
                    $center, 
                    $width, 
                    $height, 
                    $size, 
                    $startAngle, 
                    $startIteration, 
                    $color
                );
            }

            // Draw all steps
            for ( ; $startIteration < $endIteration; $startIteration += $this->options->detail )
            {
                $this->drawCircularArcStep( 
                    $center, 
                    $width, 
                    $height, 
                    $size, 
                    $startIteration, 
                    $startIteration + $this->options->detail, 
                    $color 
                );
            }

            if ( $endIteration < $endAngle )
            {
                // Draw closing step
                $this->drawCircularArcStep( 
                    $center, 
                    $width, 
                    $height, 
                    $size, 
                    $endIteration, 
                    $endAngle, 
                    $color 
                );
            }
        }
        else
        {
            imagefilledarc( 
                $image, 
                $this->supersample( $center->x ), 
                $this->supersample( $center->y ), 
                $this->supersample( $width ), 
                $this->supersample( $height ), 
                $startAngle, 
                $endAngle, 
                $drawColor, 
                IMG_ARC_PIE | IMG_ARC_NOFILL
            );
        }
    }
    
    /**
     * Draws a circle
     * 
     * @param ezcGraphCoordinate $center 
     * @param mixed $width
     * @param mixed $height
     * @param ezcGraphColor $color
     * @param bool $filled
     *
     * @return void
     */
    public function drawCircle( ezcGraphCoordinate $center, $width, $height, ezcGraphColor $color, $filled = true )
    {
        $image = $this->getImage();

        $drawColor = $this->allocate( $color );

        if ( $filled )
        {
            imagefilledellipse( 
                $image, 
                $this->supersample( $center->x ), 
                $this->supersample( $center->y ), 
                $this->supersample( $width ), 
                $this->supersample( $height ), 
                $drawColor 
            );
        }
        else
        {
            imageellipse( 
                $image, 
                $this->supersample( $center->x ), 
                $this->supersample( $center->y ), 
                $this->supersample( $width ), 
                $this->supersample( $height ), 
                $drawColor 
            );
        }
    }
    
    /**
     * Draws a imagemap of desired size
     * 
     * @param mixed $file 
     * @param ezcGraphCoordinate $position 
     * @param mixed $width 
     * @param mixed $height 
     * @return void
     */
    public function drawImage( $file, ezcGraphCoordinate $position, $width, $height )
    {
        $this->preProcessImages[] = array(
            'file' => $file, 
            'position' => clone $position,
            'width' => $width,
            'height' => $height,
        );
    }

    /**
     * Draw all images to image ressource handler
     * 
     * @param ressource $image Image to draw on
     * @return ressource Updated image ressource
     */
    protected function addImages( $image )
    {
        foreach ( $this->preProcessImages as $preImage )
        {
            $preImageData = $this->imageCreateFrom( $preImage['file'] );
            call_user_func_array(
                $this->options->resampleFunction,
                array(
                    $image,
                    $preImageData['image'],
                    $preImage['position']->x, $preImage['position']->y,
                    0, 0,
                    $preImage['width'], $preImage['height'],
                    $preImageData['width'], $preImageData['height'],
                )
            );
        }

        return $image;
    }

    /**
     * Finally save image
     * 
     * @param mixed $file 
     * @return void
     */
    public function render ( $file )
    {
        $destination = imagecreatetruecolor( $this->options->width, $this->options->height );

        // Default to a transparent white background
        $bgColor = imagecolorallocatealpha( $destination, 255, 255, 255, 127 );
        imagealphablending( $destination, true );
        imagesavealpha( $destination, true );
        imagefill( $destination, 1, 1, $bgColor );

        // Apply background if one is defined
        if ( $this->options->background !== false )
        {
            $background = $this->imageCreateFrom( $this->options->background );

            call_user_func_array(
                $this->options->resampleFunction,
                array(
                    $destination,
                    $background['image'],
                    0, 0,
                    0, 0,
                    $this->options->width, $this->options->height,
                    $background['width'], $background['height'],
                )
            );
        }

        // Draw all images to exclude them from supersampling
        $destination = $this->addImages( $destination );

        // Finally merge with graph
        $image = $this->getImage();
        call_user_func_array(
            $this->options->resampleFunction,
            array(
                $destination,
                $image,
                0, 0,
                0, 0,
                $this->options->width, $this->options->height,
                $this->supersample( $this->options->width ), $this->supersample( $this->options->height )
            )
        );

        $this->image = $destination;
        imagedestroy( $image );

        // Draw all texts
        $this->drawAllTexts();

        $image = $this->getImage();
        switch ( $this->options->imageFormat )
        {
            case IMG_PNG:
                imagepng( $image, $file );
                break;
            case IMG_JPEG:
                imagejpeg( $image, $file, $this->options->quality );
                break;
        }
    }
}

?>
OpenPOWER on IntegriCloud