Rename classes for Horde 4 CS - part two (yea case preserving filesystems!!)
authorMichael J. Rubinsky <mrubinsk@horde.org>
Wed, 27 May 2009 17:56:43 +0000 (13:56 -0400)
committerMichael J. Rubinsky <mrubinsk@horde.org>
Wed, 27 May 2009 17:56:43 +0000 (13:56 -0400)
19 files changed:
framework/Image/lib/Horde/Image/Effect/Border.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Gd/DropShadow.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Gd/RoundCorners.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Gd/TextWatermark.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Gd/UnsharpMask.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Im/Border.php [new file with mode: 0755]
framework/Image/lib/Horde/Image/Effect/Im/Composite.php [new file with mode: 0755]
framework/Image/lib/Horde/Image/Effect/Im/DropShadow.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Im/PhotoStack.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Im/PolaroidImage.php [new file with mode: 0755]
framework/Image/lib/Horde/Image/Effect/Im/RoundCorners.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Effect/Im/TextWatermark.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Exception.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Gd.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Im.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Imagick.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Png.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Svg.php [new file with mode: 0644]
framework/Image/lib/Horde/Image/Swf.php [new file with mode: 0644]

diff --git a/framework/Image/lib/Horde/Image/Effect/Border.php b/framework/Image/lib/Horde/Image/Effect/Border.php
new file mode 100644 (file)
index 0000000..dfafde9
--- /dev/null
@@ -0,0 +1,53 @@
+<?php
+/**
+ * Image border decorator for the Horde_Image package.
+ *
+ * $Horde: framework/Image/Image/Effect/border.php,v 1.1 2007/10/21 21:59:49 mrubinsk Exp $
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Border extends Horde_Image_Effect {
+
+    /**
+     * Valid parameters for border decorators:
+     *
+     *   padding         - Pixels from the image edge that the border will start.
+     *   borderColor     - Border color. Defaults to black.
+     *   fillColor       - Color to fill the border with. Defaults to white.
+     *   lineWidth       - Border thickness, defaults to 1 pixel.
+     *   roundWidth      - Width of the corner rounding. Defaults to none.
+     *
+     * @var array
+     */
+    var $_params = array('padding' => 0,
+                         'borderColor' => 'black',
+                         'fillColor' => 'white',
+                         'lineWidth' => 1,
+                         'roundWidth' => 0);
+
+    /**
+     * Draw the border.
+     *
+     * This draws the configured border to the provided image. Beware,
+     * that every pixel inside the border clipping will be overwritten
+     * with the background color.
+     */
+    function apply()
+    {
+        $o = $this->_params;
+
+        $d = $this->_image->getDimensions();
+        $x = $o['padding'];
+        $y = $o['padding'];
+        $width = $d['width'] - (2 * $o['padding']);
+        $height = $d['height'] - (2 * $o['padding']);
+
+        if ($o['roundWidth'] > 0) {
+            $this->_image->roundedRectangle($x, $y, $width, $height, $o['roundWidth'], $o['borderColor'], $o['fillColor']);
+        } else {
+            $this->_image->rectangle($x, $y, $width, $height, $o['borderColor'], $o['fillColor']);
+        }
+    }
+
+}
diff --git a/framework/Image/lib/Horde/Image/Effect/Gd/DropShadow.php b/framework/Image/lib/Horde/Image/Effect/Gd/DropShadow.php
new file mode 100644 (file)
index 0000000..b18269c
--- /dev/null
@@ -0,0 +1,124 @@
+<?php
+/**
+ * Image effect for adding a drop shadow.
+ *
+ * This algorithm is from the phpThumb project available at
+ * http://phpthumb.sourceforge.net and all credit for this script should go to
+ * James Heinrich <info@silisoftware.com>.  Modifications made to the code
+ * to fit it within the Horde framework and to adjust for our coding standards.
+ *
+ * @author Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Gd_DropShadow extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters:
+     *
+     * @TODO
+     *
+     * @var array
+     */
+    protected $_params = array('distance' => 5,
+                               'width' => 2,
+                               'hexcolor' => '000000',
+                               'angle' => 215,
+                               'fade' => 10);
+
+    /**
+     * Apply the drop_shadow effect.
+     *
+     * @return mixed true | PEAR_Error
+     */
+    public function apply()
+    {
+        $distance = $this->_params['distance'];
+        $width = $this->_params['width'];
+        $hexcolor = $this->_params['hexcolor'];
+        $angle = $this->_params['angle'];
+        $fade = $this->_params['fade'];
+
+        $width_shadow  = cos(deg2rad($angle)) * ($distance + $width);
+        $height_shadow = sin(deg2rad($angle)) * ($distance + $width);
+        $gdimg = $this->_image->_im;
+        $imgX = $this->_image->call('imageSX', array($gdimg));
+        $imgY = $this->_image->call('imageSY', array($gdimg));
+
+        $offset['x'] = cos(deg2rad($angle)) * ($distance + $width - 1);
+        $offset['y'] = sin(deg2rad($angle)) * ($distance + $width - 1);
+
+        $tempImageWidth  = $imgX  + abs($offset['x']);
+        $tempImageHeight = $imgY + abs($offset['y']);
+        $gdimg_dropshadow_temp = $this->_image->create($tempImageWidth,
+                                                        $tempImageHeight);
+        if (!is_a($gdimg_dropshadow_temp, 'PEAR_Error')) {
+            $this->_image->call('imageAlphaBlending',
+                                 array($gdimg_dropshadow_temp, false));
+
+            $this->_image->call('imageSaveAlpha',
+                                 array($gdimg_dropshadow_temp, true));
+
+            $transparent1 = $this->_image->call('imageColorAllocateAlpha', array($gdimg_dropshadow_temp, 0, 0, 0, 127));
+
+            if (is_a($transparent1, 'PEAR_Error')) {
+                return $transparent1;
+            }
+
+            $this->_image->call('imageFill',
+                                 array($gdimg_dropshadow_temp, 0, 0, $transparent1));
+
+            for ($x = 0; $x < $imgX; $x++) {
+                for ($y = 0; $y < $imgY; $y++) {
+                    $colorat = $this->_image->call('imageColorAt', array($gdimg, $x, $y));
+                    $PixelMap[$x][$y] = $this->_image->call('imageColorsForIndex',
+                                                             array($gdimg, $colorat));
+                }
+            }
+
+            /* Creates the shadow */
+            $r = hexdec(substr($hexcolor, 0, 2));
+            $g = hexdec(substr($hexcolor, 2, 2));
+            $b = hexdec(substr($hexcolor, 4, 2));
+
+            /* Essentially masks the original image and creates the shadow */
+            for ($x = 0; $x < $tempImageWidth; $x++) {
+                for ($y = 0; $y < $tempImageHeight; $y++) {
+                        if (!isset($PixelMap[$x][$y]['alpha']) ||
+                            ($PixelMap[$x][$y]['alpha'] > 0)) {
+                            if (isset($PixelMap[$x + $offset['x']][$y + $offset['y']]['alpha']) && ($PixelMap[$x + $offset['x']][$y + $offset['y']]['alpha'] < 127)) {
+                                $thisColor = $this->_image->call('imageColorAllocateAlpha', array($gdimg_dropshadow_temp, $r, $g, $b, $PixelMap[$x + $offset['x']][$y + $offset['y']]['alpha']));
+                                $this->_image->call('imageSetPixel',
+                                                     array($gdimg_dropshadow_temp, $x, $y, $thisColor));
+                            }
+                        }
+                }
+            }
+            /* Overlays the original image */
+            $this->_image->call('imageAlphaBlending',
+                                 array($gdimg_dropshadow_temp, true));
+
+            for ($x = 0; $x < $imgX; $x++) {
+                for ($y = 0; $y < $imgY; $y++) {
+                    if ($PixelMap[$x][$y]['alpha'] < 127) {
+                        $thisColor = $this->_image->call('imageColorAllocateAlpha', array($gdimg_dropshadow_temp, $PixelMap[$x][$y]['red'], $PixelMap[$x][$y]['green'], $PixelMap[$x][$y]['blue'], $PixelMap[$x][$y]['alpha']));
+                        $this->_image->call('imageSetPixel',
+                                             array($gdimg_dropshadow_temp, $x, $y, $thisColor));
+                    }
+                }
+            }
+
+            $this->_image->call('imageSaveAlpha',
+                                 array($gdimg, true));
+            $this->_image->call('imageAlphaBlending',
+                                 array($gdimg, false));
+
+            // Merge the shadow and the original into the original.
+            $this->_image->call('imageCopyResampled',
+                                 array($gdimg, $gdimg_dropshadow_temp, 0, 0, 0, 0, $imgX, $imgY, $this->_image->call('imageSX', array($gdimg_dropshadow_temp)), $this->_image->call('imageSY', array($gdimg_dropshadow_temp))));
+
+            $this->_image->call('imageDestroy', array($gdimg_dropshadow_temp));
+        }
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Gd/RoundCorners.php b/framework/Image/lib/Horde/Image/Effect/Gd/RoundCorners.php
new file mode 100644 (file)
index 0000000..b20f248
--- /dev/null
@@ -0,0 +1,135 @@
+<?php
+/**
+ * Image effect for round image corners.
+ *
+ * This algorithm is from the phpThumb project available at
+ * http://phpthumb.sourceforge.net and all credit (and complaints ;) for this
+ * script should go to James Heinrich <info@silisoftware.com>.  Modifications
+ * made to the code to fit it within the Horde framework and to adjust for our
+ * coding standards.
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Gd_RoundCorners extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters:
+     *
+     * radius - Radius of rounded corners.
+     *
+     * @var array
+     */
+    protected $_params = array('radius' => 10);
+
+    /**
+     * Apply the round_corners effect.
+     *
+     * @return mixed true | PEAR_Error
+     */
+    public function apply()
+    {
+        // Original comments from phpThumb projet:
+        // generate mask at twice desired resolution and downsample afterwards
+        // for easy antialiasing mask is generated as a white double-size
+        // elipse on a triple-size black background and copy-paste-resampled
+        // onto a correct-size mask image as 4 corners due to errors when the
+        // entire mask is resampled at once (gray edges)
+        $radius_x = $radius_y = $this->_params['radius'];
+        $gdimg = $this->_image->_im;
+        $imgX = round($this->_image->call('imageSX', array($gdimg)));
+        $imgY = round($this->_image->call('imageSY', array($gdimg)));
+
+        $gdimg_cornermask_triple = $this->_image->create(round($radius_x * 6),
+                                                          round($radius_y * 6));
+        if (!is_a($gdimg_cornermask_triple, 'PEAR_Error')) {
+
+            $gdimg_cornermask = $this->_image->create($imgX, $imgY);
+            if (!is_a($gdimg_cornermask, 'PEAR_Error')) {
+                $color_transparent = $this->_image->call('imageColorAllocate',
+                                                          array($gdimg_cornermask_triple,
+                                                                255,
+                                                                255,
+                                                                255));
+
+                $this->_image->call('imageFilledEllipse',
+                                     array($gdimg_cornermask_triple,
+                                           $radius_x * 3,
+                                           $radius_y * 3,
+                                           $radius_x * 4,
+                                           $radius_y * 4,
+                                           $color_transparent));
+
+                $this->_image->call('imageFilledRectangle',
+                                     array($gdimg_cornermask,
+                                           0,
+                                           0,
+                                           $imgX,
+                                           $imgY,
+                                           $color_transparent));
+
+                $this->_image->call('imageCopyResampled',
+                                     array($gdimg_cornermask,
+                                           $gdimg_cornermask_triple,
+                                           0,
+                                           0,
+                                           $radius_x,
+                                           $radius_y,
+                                           $radius_x,
+                                           $radius_y,
+                                           $radius_x * 2,
+                                           $radius_y * 2));
+
+                $this->_image->call('imageCopyResampled',
+                                     array($gdimg_cornermask,
+                                           $gdimg_cornermask_triple,
+                                           0,
+                                           $imgY - $radius_y,
+                                           $radius_x,
+                                           $radius_y * 3,
+                                           $radius_x,
+                                           $radius_y,
+                                           $radius_x * 2,
+                                           $radius_y * 2));
+
+                $this->_image->call('imageCopyResampled',
+                                     array($gdimg_cornermask,
+                                           $gdimg_cornermask_triple,
+                                           $imgX - $radius_x,
+                                           $imgY - $radius_y,
+                                           $radius_x * 3,
+                                           $radius_y * 3,
+                                           $radius_x,
+                                           $radius_y,
+                                           $radius_x * 2,
+                                           $radius_y * 2));
+
+                $this->_image->call('imageCopyResampled',
+                                     array($gdimg_cornermask,
+                                           $gdimg_cornermask_triple,
+                                           $imgX - $radius_x,
+                                           0,
+                                           $radius_x * 3,
+                                           $radius_y,
+                                           $radius_x,
+                                           $radius_y,
+                                           $radius_x * 2,
+                                           $radius_y * 2));
+
+                $result = $this->_image->_applyMask($gdimg_cornermask);
+                if (is_a($result, 'PEAR_Error')) {
+                    return $result;
+                }
+                $this->_image->call('imageDestroy', array($gdimg_cornermask));
+                return true;
+            } else {
+                return $gdimg_cornermas; // PEAR_Error
+            }
+            $this->_image->call('imageDestroy',
+                                 array($gdimg_cornermask_triple));
+        } else {
+            return $gdimg_cornermas_triple; // PEAR_Error
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Gd/TextWatermark.php b/framework/Image/lib/Horde/Image/Effect/Gd/TextWatermark.php
new file mode 100644 (file)
index 0000000..098a503
--- /dev/null
@@ -0,0 +1,122 @@
+<?php
+/**
+ * Image effect for watermarking images with text for the GD driver..
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Gd_TextWatermark extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for watermark effects:
+     *
+     *   text (required)  - The text of the watermark.
+     *   halign           - The horizontal placement
+     *   valign           - The vertical placement
+     *   font             - The font name or family to use
+     *   fontsize         - The size of the font to use
+     *                      (small, medium, large, giant)
+     *
+     * @var array
+     */
+    protected $_params = array('halign' => 'right',
+                               'valign' => 'bottom',
+                               'font' => 'courier',
+                               'fontsize' => 'small');
+    /**
+     * Add the watermark
+     */
+    public function apply()
+    {
+        $color = $this->_image->call('imageColorClosest',
+                                      array($this->_image->_im, 255, 255, 255));
+        if (is_a($color, 'PEAR_Error')) {
+            return $color;
+        }
+        $shadow = $this->_image->call('imageColorClosest',
+                                       array($this->_image->_im, 0, 0, 0));
+        if (is_a($shadow, 'PEAR_Error')) {
+            return $shadow;
+        }
+
+        // Shadow offset in pixels.
+        $drop = 1;
+
+        // Maximum text width.
+        $maxwidth = 200;
+
+        // Amount of space to leave between the text and the image border.
+        $padding = 10;
+
+        $f = $this->_image->getFont($this->_params['fontsize']);
+        $fontwidth = $this->_image->call('imageFontWidth', array($f));
+        if (is_a($fontwidth, 'PEAR_Error')) {
+            return $fontwidth;
+        }
+        $fontheight = $this->_image->call('imageFontHeight', array($f));
+        if (is_a($fontheight, 'PEAR_Error')) {
+            return $fontheight;
+        }
+
+        // So that shadow is not off the image with right align and bottom valign.
+        $margin = floor($padding + $drop) / 2;
+        if ($maxwidth) {
+            $maxcharsperline = floor(($maxwidth - ($margin * 2)) / $fontwidth);
+            $text = wordwrap($this->_params['text'], $maxcharsperline, "\n", 1);
+        }
+
+        // Split $text into individual lines.
+        $lines = explode("\n", $text);
+
+        switch ($this->_params['valign']) {
+        case 'center':
+            $y = ($this->_image->call('imageSY', array($this->_image->_im)) - ($fontheight * count($lines))) / 2;
+            break;
+
+        case 'bottom':
+            $y = $this->_image->call('imageSY', array($this->_image->_im)) - (($fontheight * count($lines)) + $margin);
+            break;
+
+        default:
+            $y = $margin;
+            break;
+        }
+
+        switch ($this->_params['halign']) {
+        case 'right':
+            foreach ($lines as $line) {
+                if (is_a($result = $this->_image->call('imageString', array($this->_image->_im, $f, ($this->_image->call('imageSX', array($this->_image->_im)) - $fontwidth * strlen($line)) - $margin + $drop, ($y + $drop), $line, $shadow)), 'PEAR_Error')) {
+                    return $result;
+                }
+                $result = $this->_image->call('imageString', array($this->_image->_im, $f, ($this->_image->call('imageSX', array($this->_image->_im)) - $fontwidth * strlen($line)) - $margin, $y, $line, $color));
+                $y += $fontheight;
+            }
+            break;
+
+        case 'center':
+            foreach ($lines as $line) {
+                if (is_a($result = $this->_image->call('imageString', array($this->_image->_im, $f, floor(($this->_image->call('imageSX', array($this->_image->_im)) - $fontwidth * strlen($line)) / 2) + $drop, ($y + $drop), $line, $shadow)), 'PEAR_Error')) {
+                    return $result;
+                }
+                $result = $this->_image->call('imageString', array($this->_image->_im, $f, floor(($this->_image->call('imageSX', array($this->_image->_im)) - $fontwidth * strlen($line)) / 2), $y, $line, $color));
+                $y += $fontheight;
+            }
+            break;
+
+        default:
+            foreach ($lines as $line) {
+                if (is_a($result = $this->_image->call('imageString', array($this->_image->_im, $f, $margin + $drop, ($y + $drop), $line, $shadow)), 'PEAR_Error')) {
+                    return $result;
+                }
+                $result = $this->_image->call('imageString', array($this->_image->_im, $f, $margin, $y, $line, $color));
+                $y += $fontheight;
+            }
+            break;
+        }
+
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Gd/UnsharpMask.php b/framework/Image/lib/Horde/Image/Effect/Gd/UnsharpMask.php
new file mode 100644 (file)
index 0000000..8a29a1e
--- /dev/null
@@ -0,0 +1,134 @@
+<?php
+/**
+ * Unsharp mask Image effect.
+ *
+ * Unsharp mask algorithm by Torstein Hønsi 2003 <thoensi_at_netcom_dot_no>
+ * From: http://www.vikjavev.com/hovudsida/umtestside.php
+ *
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Gd_UnsharpMask extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters:
+     *
+     * @TODO
+     *
+     * @var array
+     */
+    protected $_params = array('amount' => 0,
+                               'radius' => 0,
+                               'threshold' => 0);
+
+    /**
+     * Apply the unsharp_mask effect.
+     *
+     * @return mixed true | PEAR_Error
+     */
+    public function apply()
+    {
+        $amount = $this->_params['amount'];
+        $radius = $this->_params['radius'];
+        $threshold = $this->_params['threshold'];
+
+        // Attempt to calibrate the parameters to Photoshop:
+        $amount = min($amount, 500);
+        $amount = $amount * 0.016;
+        if ($amount == 0) {
+            return true;
+        }
+
+        $radius = min($radius, 50);
+        $radius = $radius * 2;
+
+        $threshold = min($threshold, 255);
+
+        $radius = abs(round($radius));  // Only integers make sense.
+        if ($radius == 0) {
+            return true;
+        }
+
+        $img = $this->_image->_im;
+        $w = ImageSX($img);
+        $h = ImageSY($img);
+        $imgCanvas  = ImageCreateTrueColor($w, $h);
+        $imgCanvas2 = ImageCreateTrueColor($w, $h);
+        $imgBlur    = ImageCreateTrueColor($w, $h);
+        $imgBlur2   = ImageCreateTrueColor($w, $h);
+        ImageCopy($imgCanvas,  $img, 0, 0, 0, 0, $w, $h);
+        ImageCopy($imgCanvas2, $img, 0, 0, 0, 0, $w, $h);
+
+        // Gaussian blur matrix:
+        //
+        //  1   2   1
+        //  2   4   2
+        //  1   2   1
+        //
+        //////////////////////////////////////////////////
+
+        // Move copies of the image around one pixel at the time and merge them with weight
+        // according to the matrix. The same matrix is simply repeated for higher radii.
+        for ($i = 0; $i < $radius; $i++)    {
+            ImageCopy     ($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1);            // up left
+            ImageCopyMerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w,     $h,     50);        // down right
+            ImageCopyMerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h,     33.33333);  // down left
+            ImageCopyMerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w,     $h - 1, 25);        // up right
+            ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h,     33.33333);  // left
+            ImageCopyMerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w,     $h,     25);        // right
+            ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w,     $h - 1, 20 );       // up
+            ImageCopyMerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w,     $h,     16.666667); // down
+            ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w,     $h,     50);        // center
+            ImageCopy     ($imgCanvas, $imgBlur, 0, 0, 0, 0, $w,     $h);
+
+            // During the loop above the blurred copy darkens, possibly due to a roundoff
+            // error. Therefore the sharp picture has to go through the same loop to
+            // produce a similar image for comparison. This is not a good thing, as processing
+            // time increases heavily.
+            ImageCopy     ($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 20 );
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 16.666667);
+            ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
+            ImageCopy     ($imgCanvas2, $imgBlur2, 0, 0, 0, 0, $w, $h);
+        }
+
+        // Calculate the difference between the blurred pixels and the original
+        // and set the pixels
+        for ($x = 0; $x < $w; $x++) { // each row
+            for ($y = 0; $y < $h; $y++) { // each pixel
+
+                $rgbOrig = ImageColorAt($imgCanvas2, $x, $y);
+                $rOrig = (($rgbOrig >> 16) & 0xFF);
+                $gOrig = (($rgbOrig >>  8) & 0xFF);
+                $bOrig =  ($rgbOrig        & 0xFF);
+
+                $rgbBlur = ImageColorAt($imgCanvas, $x, $y);
+                $rBlur = (($rgbBlur >> 16) & 0xFF);
+                $gBlur = (($rgbBlur >>  8) & 0xFF);
+                $bBlur =  ($rgbBlur        & 0xFF);
+
+                // When the masked pixels differ less from the original
+                // than the threshold specifies, they are set to their original value.
+                $rNew = (abs($rOrig - $rBlur) >= $threshold) ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig)) : $rOrig;
+                $gNew = (abs($gOrig - $gBlur) >= $threshold) ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig)) : $gOrig;
+                $bNew = (abs($bOrig - $bBlur) >= $threshold) ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig)) : $bOrig;
+
+                if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {
+                    $pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew);
+                    ImageSetPixel($img, $x, $y, $pixCol);
+                }
+            }
+        }
+        ImageDestroy($imgCanvas);
+        ImageDestroy($imgCanvas2);
+        ImageDestroy($imgBlur);
+        ImageDestroy($imgBlur2);
+
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/Border.php b/framework/Image/lib/Horde/Image/Effect/Im/Border.php
new file mode 100755 (executable)
index 0000000..f2bebe6
--- /dev/null
@@ -0,0 +1,48 @@
+<?php
+/**
+ * Image border Effect for the Horde_Image package.
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_Border extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for border effects:
+     *
+     *   bordercolor     - Border color. Defaults to black.
+     *   borderwidth     - Border thickness, defaults to 1 pixel.
+     *   preserve        - Preserves the alpha transparency layer (if present)
+     *
+     * @var array
+     */
+    protected $_params = array('bordercolor' => 'black',
+                               'borderwidth' => 1,
+                               'preserve' => true);
+
+    /**
+     * Draw the border.
+     *
+     * This draws the configured border to the provided image. Beware,
+     * that every pixel inside the border clipping will be overwritten
+     * with the background color.
+     */
+    public function apply()
+    {
+        if (!is_null($this->_image->_imagick)) {
+             $this->_image->_imagick->borderImage(
+                $this->_params['bordercolor'],
+                $this->_params['borderwidth'],
+                $this->_params['borderwidth']);
+        } else {
+            $this->_image->addPostSrcOperation(sprintf(
+                "   -bordercolor \"%s\" %s -border %s",
+                $this->_params['bordercolor'],
+                (!empty($this->_params['preserve']) ? '-compose Copy' : ''),
+                $this->_params['borderwidth']));
+        }
+
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/Composite.php b/framework/Image/lib/Horde/Image/Effect/Im/Composite.php
new file mode 100755 (executable)
index 0000000..15bf207
--- /dev/null
@@ -0,0 +1,83 @@
+<?php
+/**
+ * Simple composite effect for composing multiple images. This effect assumes
+ * that all images being passed in are already the desired size.
+ *
+ * Copyright 2009 The Horde Project (http://www.horde.org)
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_Composite extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for border effects:
+     *
+     * 'images'  - an array of Horde_Image objects to overlay.
+     *
+     *  ...and ONE of the following. If both are provided, the behaviour is
+     *  undefined.
+     *
+     * 'gravity'    - the ImageMagick gravity constant describing placement
+     *                (IM driver only so far, not imagick)
+     *
+     * 'x' and 'y'  - coordinates for the overlay placement.
+     *
+     * @var array
+     */
+    protected $_params = array();
+
+    /**
+     * Draw the border.
+     *
+     * This draws the configured border to the provided image. Beware,
+     * that every pixel inside the border clipping will be overwritten
+     * with the background color.
+     */
+    public function apply()
+    {
+        $this->_image->_imagick = null;
+        if (!is_null($this->_image->_imagick)) {
+            foreach ($this->_params['images'] as $image) {
+                $topimg = new Horde_Image_ImagickProxy();
+                $topimg->clear();
+                $topimg->readImageBlob($image->raw());
+
+                /* Calculate center for composite (gravity center)*/
+                $geometry = $this->_image->_imagick->getImageGeometry();
+                $x = $geometry['width'] / 2;
+                $y = $geometry['height'] / 2;
+
+                if (isset($this->_params['x']) && isset($this->_params['y'])) {
+                    $x = $this->_params['x'];
+                    $y = $this->_params['y'];
+                }
+                $this->_image->_imagick->compositeImage($topimg, constant('Imagick::COMPOSITE_OVER'), $x, $y);
+            }
+        } else {
+            $ops = $geometry = $gravity = '';
+            if (isset($this->_params['gravity'])) {
+                $gravity = ' -gravity ' . $this->_params['gravity'];
+            }
+
+            if (isset($this->_params['x']) && isset($this->_params['y'])) {
+                $geometry = ' -geometry +' . $this->_params['x'] . '+' . $this->_params['y'] . ' ';
+            }
+            if (isset($this->_params['compose'])) {
+                // The -matte ensures that the destination (background) image
+                // has an alpha channel - to avoid black holes in the image.
+                $compose = ' -compose ' . $this->_params['compose'] . ' -matte';
+            }
+
+            foreach($this->_params['images'] as $image) {
+                $temp = $image->toFile();
+                $this->_image->addFileToClean($temp);
+                $ops .= ' ' . $temp . $gravity . $compose . ' -composite';
+            }
+            $this->_image->addOperation($geometry);
+            $this->_image->addPostSrcOperation($ops);
+        }
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/DropShadow.php b/framework/Image/lib/Horde/Image/Effect/Im/DropShadow.php
new file mode 100644 (file)
index 0000000..83a504a
--- /dev/null
@@ -0,0 +1,84 @@
+<?php
+/**
+ * Image effect for adding a drop shadow.
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_DropShadow extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters: Most are currently ignored for the im version
+     * of this effect.
+     *
+     * @TODO
+     *
+     * @var array
+     */
+    protected $_params = array('distance' => 5, // This is used as the x and y offset
+                               'width' => 2,
+                               'hexcolor' => '000000',
+                               'angle' => 215,
+                               'fade' => 3, // Sigma value
+                               'padding' => 0,
+                               'background' => 'none');
+
+    /**
+     * Apply the effect.
+     *
+     * @return mixed true | PEAR_Error
+     */
+    public function apply()
+    {
+        if (!is_null($this->_image->_imagick)) {
+            // $shadow is_a ImagickProxy object
+            $shadow = $this->_image->_imagick->cloneIM();
+            $shadow->setImageBackgroundColor('black');
+            $shadow->shadowImage(80, $this->_params['fade'],
+                                 $this->_params['distance'],
+                                 $this->_params['distance']);
+
+
+            // If we have an actual background color, we need to explicitly
+            // create a new background image with that color to be sure there
+            // *is* a background color.
+            if ($this->_params['background'] != 'none') {
+                $size = $shadow->getImageGeometry();
+                $new = new Horde_Image_ImagickProxy($size['width'],
+                                                    $size['height'],
+                                                    $this->_params['background'],
+                                                    $this->_image->getType());
+
+                $new->compositeImage($shadow,
+                                     constant('Imagick::COMPOSITE_OVER'), 0, 0);
+                $shadow->clear();
+                $shadow->addImage($new);
+                $new->destroy();
+            }
+
+            if ($this->_params['padding']) {
+                $shadow->borderImage($this->_params['background'],
+                                     $this->_params['padding'],
+                                     $this->_params['padding']);
+            }
+            $shadow->compositeImage($this->_image->_imagick,
+                                    constant('Imagick::COMPOSITE_OVER'),
+                                    0, 0);
+            $this->_image->_imagick->clear();
+            $this->_image->_imagick->addImage($shadow);
+            $shadow->destroy();
+        } else {
+            $size = $this->_image->getDimensions();
+//            $this->_image->addPostSrcOperation("-size {$size['width']}x{$size['height']} xc:{$this->_params['background']} "
+//                . "-fill {$this->_params['background']} -draw \"matte 0,0 reset\"");
+            $this->_image->addPostSrcOperation('\( +clone -background black -shadow 80x' . $this->_params['fade'] . '+' . $this->_params['distance'] . '+' . $this->_params['distance'] . ' \) +swap -background none -flatten +repage -bordercolor ' . $this->_params['background'] . ' -border ' . $this->_params['padding']);
+        }
+        $this->_image->_width = 0;
+        $this->_image->_height = 0;
+
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/PhotoStack.php b/framework/Image/lib/Horde/Image/Effect/Im/PhotoStack.php
new file mode 100644 (file)
index 0000000..d9678ab
--- /dev/null
@@ -0,0 +1,328 @@
+<?php
+/**
+ * Effect for composing multiple images into a single image.
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * The technique for the Polaroid-like stack using the Imagick extension is
+ * credited to Mikko Koppanen and is documented at http://valokuva.org
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_PhotoStack extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for the stack effect
+     *
+     * images           -    An array of Horde_Image objects to stack. Images
+     *                       are stacked in a FIFO manner, so that the top-most
+     *                       image is the last one in this array.
+     *
+     * type             -    Determines the style for the composition.
+     *                       'plain' or 'polaroid' are supported.
+     *
+     * resize_height    -    The height that each individual thumbnail
+     *                       should be resized to before composing on the image.
+     *
+     * padding          -    How much padding should we ensure is left around
+     *                       the active image area?
+     *
+     * background       -    The background canvas color - this is used as the
+     *                       color to set any padding to.
+     *
+     * bordercolor      -    If using type 'plain' this sets the color of the
+     *                       border that each individual thumbnail gets.
+     *
+     * borderwidth      -    If using type 'plain' this sets the width of the
+     *                       border on each individual thumbnail.
+     *
+     * offset           -    If using type 'plain' this determines the amount of
+     *                       x and y offset to give each successive image when
+     *                       it is placed on the top of the stack.
+     *
+     * @var array
+     */
+    protected $_params = array('type' => 'plain',
+                               'resize_height' => '150',
+                               'padding' => 0,
+                               'background' => 'none',
+                               'bordercolor' => '#333',
+                               'borderwidth' => 1,
+                               'borderrounding' => 10,
+                               'offset' => 5);
+
+    /**
+     * Create the photo_stack
+     *
+     */
+    public function apply()
+    {
+        $i = 1;
+        $cnt = count($this->_params['images']);
+        if ($cnt <=0) {
+            return PEAR::raiseError('No images provided');
+        }
+        if (!is_null($this->_image->_imagick) &&
+            $this->_image->_imagick->methodExists('polaroidImage') &&
+            $this->_image->_imagick->methodExists('trimImage')) {
+
+            $imgs = array();
+            $length = 0;
+
+            switch ($this->_params['type']) {
+            case 'plain':
+            case 'rounded':
+                $haveBottom = false;
+                // First, we need to resize the top image to get the dimensions
+                // for the rest of the stack.
+                $topimg = new Horde_Image_ImagickProxy();
+                $topimg->clear();
+                $topimg->readImageBlob($this->_params['images'][$cnt - 1]->raw());
+                $topimg->thumbnailImage(
+                    $this->_params['resize_height'],
+                    $this->_params['resize_height'],
+                    true);
+                if ($this->_params['type'] == 'rounded') {
+                    $topimg = $this->_roundBorder($topimg);
+                }
+
+                $size = $topimg->getImageGeometry();
+                foreach ($this->_params['images'] as $image) {
+                    $imgk= new Horde_Image_ImagickProxy();
+                    $imgk->clear();
+                    $imgk->readImageBlob($image->raw());
+                    if ($i++ <= $cnt) {
+                        $imgk->thumbnailImage($size['width'], $size['height'],
+                                              false);
+                    } else {
+                        $imgk->destroy();
+                        $imgk = $topimg->cloneIM();
+                    }
+
+                    if ($this->_params['type'] == 'rounded') {
+                        $imgk = $this->_roundBorder($imgk);
+                    } else {
+                        $imgk->borderImage($this->_params['bordercolor'], 1, 1);
+                    }
+                    // Only shadow the bottom image for 'plain' stacks
+                    if (!$haveBottom) {
+                        $shad = $imgk->cloneIM();
+                        $shad->setImageBackgroundColor('black');
+                        $shad->shadowImage(80, 4, 0, 0);
+                        $shad->compositeImage($imgk,
+                                              constant('Imagick::COMPOSITE_OVER'),
+                                              0, 0);
+                        $imgk->clear();
+                        $imgk->addImage($shad);
+                        $shad->destroy();
+                        $haveBottom = true;
+                    }
+                    // Get the geometry of the image and remember the largest.
+                    $geo = $imgk->getImageGeometry();
+                    $length = max(
+                        $length,
+                        sqrt(pow($geo['height'], 2) + pow($geo['width'], 2)));
+
+                    $imgs[] = $imgk;
+                }
+                break;
+            case 'polaroid':
+                foreach ($this->_params['images'] as $image) {
+                    $imgk= new Horde_Image_ImagickProxy();
+                    $imgk->clear();
+                    $imgk->readImageBlob($image->raw());
+                    $imgk->thumbnailImage($this->_params['resize_height'],
+                                          $this->_params['resize_height'],
+                                          true);
+                    $imgk->setImageBackgroundColor('black');
+                    if ($i++ == $cnt) {
+                        $angle = 0;
+                    } else {
+                        $angle = mt_rand(1, 45);
+                        if (mt_rand(1, 2) % 2 === 0) {
+                            $angle = $angle * -1;
+                        }
+                    }
+                    $result = $imgk->polaroidImage($angle);
+                    if (is_a($result, 'PEAR_Error')) {
+                        return $result;
+                    }
+                     // Get the geometry of the image and remember the largest.
+                    $geo = $imgk->getImageGeometry();
+                    $length = max(
+                        $length,
+                        sqrt(pow($geo['height'], 2) + pow($geo['width'], 2)));
+
+                    $imgs[] = $imgk;
+                }
+                break;
+            }
+
+            // Make sure the background canvas is large enough to hold it all.
+            $this->_image->_imagick->thumbnailImage($length * 1.5 + 20,
+                                                    $length * 1.5 + 20);
+
+            // x and y offsets.
+            $xo = $yo = (count($imgs) + 1) * $this->_params['offset'];
+            foreach ($imgs as $image) {
+                if ($this->_params['type'] == 'polaroid') {
+                    $xo = mt_rand(1, $this->_params['resize_height'] / 2);
+                    $yo = mt_rand(1, $this->_params['resize_height'] / 2);
+                } elseif ($this->_params['type'] == 'plain' ||
+                          $this->_params['type'] == 'rounded') {
+                    $xo -= $this->_params['offset'];
+                    $yo -= $this->_params['offset'];
+                }
+
+                $this->_image->_imagick->compositeImage(
+                    $image, constant('Imagick::COMPOSITE_OVER'), $xo, $yo);
+                $image->removeImage();
+                $image->destroy();
+            }
+            // If we have a background other than 'none' we need to
+            // compose two images together to make sure we *have* a background.
+            if ($this->_params['background'] != 'none') {
+                $size = $this->_image->getDimensions();
+                $new = new Horde_Image_ImagickProxy($length * 1.5 + 20,
+                                                    $length * 1.5 + 20,
+                                                    $this->_params['background'],
+                                                    $this->_image->getType());
+
+
+
+                $new->compositeImage($this->_image->_imagick,
+                                     constant('Imagick::COMPOSITE_OVER'), 0, 0);
+                $this->_image->_imagick->clear();
+                $this->_image->_imagick->addImage($new);
+                $new->destroy();
+            }
+            // Trim the canvas before resizing to keep the thumbnails as large
+            // as possible.
+            $this->_image->_imagick->trimImage(0);
+            if ($this->_params['padding']) {
+                $this->_image->_imagick->borderImage($this->_params['background'],
+                                                     $this->_params['padding'],
+                                                     $this->_params['padding']);
+            }
+
+        } else {
+            // No Imagick installed - use im, but make sure we don't mix imagick
+            // and convert.
+            $this->_image->_imagick = null;
+            $this->_image->raw();
+
+            switch ($this->_params['type']) {
+            case 'plain':
+            case 'rounded':
+                // Get top image dimensions, then force each bottom image to the
+                // same dimensions.
+                $this->_params['images'][$cnt - 1]->resize($this->_params['resize_height'],
+                                                           $this->_params['resize_height'],
+                                                           true);
+                $size = $this->_params['images'][$cnt - 1]->getDimensions();
+                //$this->_image->resize(2 * $this->_params['resize_height'], 2 * $this->_params['resize_height']);
+                for ($i = 0; $i < $cnt; $i++) {
+                    $this->_params['images'][$i]->resize($size['height'], $size['width'], false);
+                }
+                $xo = $yo = (count($this->_params['images']) + 1) * $this->_params['offset'];
+                $ops = '';
+                $haveBottom = false;
+                foreach ($this->_params['images'] as $image) {
+                    $xo -= $this->_params['offset'];
+                    $yo -= $this->_params['offset'];
+
+                    if ($this->_params['type'] == 'rounded') {
+                        $temp = $this->_roundBorder($image);
+                    } else {
+                        $temp = $image->toFile();
+                    }
+                    $this->_image->addFileToClean($temp);
+                    $ops .= ' \( ' . $temp . ' -background none -thumbnail ' . $size['width'] . 'x' . $size['height'] . '! -repage +' . $xo . '+' . $yo . ($this->_params['type'] == 'plain' ? ' -bordercolor "#333" -border 1 ' : ' ' ) . ((!$haveBottom) ? '\( +clone -shadow 80x4+0+0 \) +swap -mosaic' : '') . ' \) ';
+                    $haveBottom = true;
+                }
+
+                // The first -background none option below is only honored in
+                // convert versions before 6.4 it seems. Without it specified as
+                // none here, all stacks come out with a white background.
+                $this->_image->addPostSrcOperation($ops . ' -background ' . $this->_params['background'] . ' -mosaic -bordercolor ' . $this->_params['background'] . ' -border ' . $this->_params['padding']);
+
+                break;
+
+            case 'polaroid':
+                // Check for im version > 6.3.2
+                $ver = $this->_image->getIMVersion();
+                if (is_array($ver) && version_compare($ver[0], '6.3.2') >= 0) {
+                    $ops = '';
+                    foreach ($this->_params['images'] as $image) {
+                        $temp = $image->toFile();
+                        // Remember the temp files so we can nuke them later.
+                        $this->_image->addFileToClean($temp);
+
+                        // Don't rotate the top image.
+                        if ($i++ == $cnt) {
+                            $angle = 0;
+                        } else {
+                            $angle = mt_rand(1, 45);
+                            if (mt_rand(1, 2) % 2 === 0) {
+                                $angle = $angle * -1;
+                            }
+                        }
+                        $ops .= ' \( ' . $temp . ' -geometry +' . mt_rand(1, $this->_params['resize_height']) . '+' . mt_rand(1, $this->_params['resize_height']) . ' -thumbnail \'' . $this->_params['resize_height'] . 'x' . $this->_params['resize_height'] . '>\' -bordercolor Snow -border 1 -polaroid ' . $angle . ' \) ';
+                    }
+                    $this->_image->addPostSrcOperation('-background none' . $ops . '-mosaic -bordercolor ' . $this->_params['background'] . ' -border ' . $this->_params['padding']);
+                } else {
+                    // An attempt at a -polaroid command free version of this
+                    // effect based on various examples and ideas at
+                    // http://imagemagick.org
+                    $ops = '';
+                    foreach ($this->_params['images'] as $image) {
+                        $temp = $image->toFile();
+                        $this->_image->addFileToClean($temp);
+                        if ($i++ == $cnt) {
+                            $angle = 0;
+                        } else {
+                            $angle = mt_rand(1, 45);
+                            if (mt_rand(1, 2) % 2 === 0) {
+                                $angle = $angle * -1;
+                            }
+                        }
+                        $ops .= '\( ' . $temp . ' -thumbnail \'' . $this->_params['resize_height'] . 'x' . $this->_params['resize_height']. '>\' -bordercolor "#eee" -border 4 -bordercolor grey90 -border 1 -bordercolor none -background none -rotate ' . $angle . ' -background none \( +clone -shadow 60x4+4+4 \) +swap -background none -flatten \) ';
+                    }
+                    $this->_image->addPostSrcOperation('-background none ' . $ops . '-mosaic -trim +repage -bordercolor ' . $this->_params['background'] . ' -border ' . $this->_params['padding']);
+                }
+                break;
+            }
+        }
+
+        return true;
+    }
+
+    private function _roundBorder($image)
+    {
+        $context = array('tmpdir' => $this->_image->getTmpDir(),
+                         'convert' => $this->_image->getConvertPath());
+        if (!is_null($this->_image->_imagick)) {
+            $size = $image->getImageGeometry();
+            $new = Horde_Image::factory('im', array('context' => $context));
+            $new->loadString('somestring', $image->getImageBlob());
+            $image->destroy();
+            $new->addEffect('round_corners', array('border' => 2, 'bordercolor' => '#111'));
+            $new->applyEffects();
+            $return  = new Horde_Image_ImagickProxy($size['width'] + $this->_params['borderwidth'],
+                                                $size['height'] + $this->_params['borderwidth'],
+                                                $this->_params['bordercolor'],
+                                                $this->_image->getType());
+            $return->clear();
+            $return->readImageBlob($new->raw());
+            return $return;
+        } else {
+            $size = $image->getDimensions();
+            $new = Horde_Image::factory('im', array('data' => $image->raw(), 'context' => $context));
+            $new->addEffect('round_corners', array('border' => 2, 'bordercolor' => '#111', 'background' => 'none'));
+            $new->applyEffects();
+            return $new->toFile();
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/PolaroidImage.php b/framework/Image/lib/Horde/Image/Effect/Im/PolaroidImage.php
new file mode 100755 (executable)
index 0000000..cd93d89
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+/**
+ * Effect for creating a polaroid looking image.
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_PolaroidImage extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for the polaroid effect
+     *
+     * resize_height    -    The height that each individual thumbnail
+     *                       should be resized to before composing on the image.
+     *
+     * background       -    The color of the image background.
+     *
+     * angle            -    Angle to rotate the image.
+     *
+     * shadowcolor      -    The color of the image shadow.
+     */
+
+    /**
+     * @var array
+     */
+    protected $_params = array('background' => 'none',
+                               'angle' => 0,
+                               'shadowcolor' => 'black');
+
+    /**
+     * Create the effect
+     *
+     */
+    public function apply()
+    {
+        if (!is_null($this->_image->_imagick) &&
+            $this->_image->_imagick->methodExists('polaroidImage') &&
+            $this->_image->_imagick->methodExists('trimImage')) {
+
+           // This determines the color of the underlying shadow.
+           $this->_image->_imagick->setImageBackgroundColor($this->_params['shadowcolor']);
+
+            $result = $this->_image->_imagick->polaroidImage($this->_params['angle']);
+            if (is_a($result, 'PEAR_Error')) {
+                return $result;
+            }
+
+            // We need to create a new image to composite the polaroid over.
+            // (yes, even if it's a transparent background evidently)
+            $size = $this->_image->getDimensions();
+            $imk = new Horde_Image_ImagickProxy($size['width'],
+                                                $size['height'],
+                                                $this->_params['background'],
+                                                $this->_image->getType());
+
+            $result = $imk->compositeImage($this->_image->_imagick,
+                                       constant('Imagick::COMPOSITE_OVER'),
+                                       0, 0);
+            if (is_a($result, 'PEAR_Error')) {
+                return $result;
+            }
+            $this->_image->_imagick->clear();
+            $this->_image->_imagick->addImage($imk);
+            $imk->destroy();
+
+        } else {
+
+            // Check for im version > 6.3.2
+            $this->_image->_imagick = null;
+            $ver = $this->_image->getIMVersion();
+            if (is_array($ver) && version_compare($ver[0], '6.3.2') >= 0) {
+                $this->_image->addPostSrcOperation(sprintf("-bordercolor \"#eee\" -background none -polaroid %s \( +clone -fill %s -draw 'color 0,0 reset' \) +swap +flatten",
+                                                              $this->_params['angle'], $this->_params['background']));
+            } else {
+                $size = $this->_image->getDimensions();
+                $this->_image->addPostSrcOperation(sprintf("-bordercolor \"#eee\" -border 8 bordercolor grey90 -border 1 -bordercolor none -background none -rotate %s \( +clone -shadow 60x1.5+1+1 -rotate 90 -wave 1x%s -rotate 90 \) +swap -rotate 90 -wave 1x%s -rotate -90 -flatten \( +clone -fill %s -draw 'color 0,0 reset ' \) +swap -flatten",
+                                                               $this->_params['angle'], $size['height'] * 2, $size['height'] * 2, $this->_params['background']));
+            }
+
+            return true;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/RoundCorners.php b/framework/Image/lib/Horde/Image/Effect/Im/RoundCorners.php
new file mode 100644 (file)
index 0000000..c56e7f4
--- /dev/null
@@ -0,0 +1,105 @@
+<?php
+/**
+ * Image effect for rounding image corners.
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_RoundCorners extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters:
+     *
+     *  radius - Radius of rounded corners.
+     *
+     * @var array
+     */
+    protected $_params = array('radius' => 10,
+                               'background' => 'none',
+                               'border' => 0,
+                               'bordercolor' => 'none');
+
+    public function apply()
+    {
+        /* Use imagick extension if available */
+        $round = $this->_params['radius'];
+        // Apparently roundCorners() requires imagick to be compiled against
+        // IM > 6.2.8.
+        if (!is_null($this->_image->_imagick) &&
+            $this->_image->_imagick->methodExists('roundCorners')) {
+            $result = $this->_image->_imagick->roundCorners($round, $round);
+            if (is_a($result, 'PEAR_Error')) {
+                return $result;
+            }
+
+            // Using a border?
+            if ($this->_params['bordercolor'] != 'none' &&
+                $this->_params['border'] > 0) {
+
+                $size = $this->_image->getDimensions();
+
+                $new = new Horde_Image_ImagickProxy($size['width'] + $this->_params['border'],
+                                                    $size['height'] + $this->_params['border'],
+                                                    $this->_params['bordercolor'],
+                                                    $this->_image->getType());
+
+                $result = $new->roundCorners($round, $round);
+                if (is_a($result, 'PEAR_Error')) {
+                    return $result;
+                }
+                $new->compositeImage($this->_image->_imagick,
+                                     constant('Imagick::COMPOSITE_OVER'), 1, 1);
+                $this->_image->_imagick->clear();
+                $this->_image->_imagick->addImage($new);
+                $new->destroy();
+            }
+
+            // If we have a background other than 'none' we need to
+            // compose two images together to make sure we *have* a background.
+            if ($this->_params['background'] != 'none') {
+                $size = $this->_image->getDimensions();
+                $new = new Horde_Image_ImagickProxy($size['width'],
+                                                    $size['height'],
+                                                    $this->_params['background'],
+                                                    $this->_image->getType());
+
+
+
+                $new->compositeImage($this->_image->_imagick,
+                                     constant('Imagick::COMPOSITE_OVER'), 0, 0);
+                $this->_image->_imagick->clear();
+                $this->_image->_imagick->addImage($new);
+                $new->destroy();
+            }
+        } else {
+            // Get image dimensions
+            $dimensions = $this->_image->getDimensions();
+            $height = $dimensions['height'];
+            $width = $dimensions['width'];
+
+            // Make sure we don't attempt to use Imagick for any other effects
+            // to make sure we do them in the proper order.
+            $this->_image->_imagick = null;
+
+            $this->_image->addOperation("-size {$width}x{$height} xc:{$this->_params['background']} "
+                . "-fill {$this->_params['background']} -draw \"matte 0,0 reset\" -tile");
+
+            $this->_image->roundedRectangle(round($round / 2),
+                                    round($round / 2),
+                                    $width - round($round / 2) - 2,
+                                    $height - round($round / 2) - 2,
+                                    $round + 2,
+                                    'none',
+                                    'white');
+        }
+
+        // Reset width/height since these might have changed
+        $this->_image->_width = 0;
+        $this->_image->_height = 0;
+
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Effect/Im/TextWatermark.php b/framework/Image/lib/Horde/Image/Effect/Im/TextWatermark.php
new file mode 100644 (file)
index 0000000..5d5c912
--- /dev/null
@@ -0,0 +1,73 @@
+<?php
+/**
+ * Image effect for watermarking images with text for the im driver..
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Effect_Im_TextWatermark extends Horde_Image_Effect
+{
+    /**
+     * Valid parameters for watermark effects:
+     *
+     *   text (required)  - The text of the watermark.
+     *   halign           - The horizontal placement
+     *   valign           - The vertical placement
+     *   font             - The font name or family to use
+     *   fontsize         - The size of the font to use
+     *                      (small, medium, large, giant)
+     *
+     * @var array
+     */
+    protected $_params = array('halign' => 'right',
+                               'valign' => 'bottom',
+                               'font' => 'courier',
+                               'fontsize' => 'small');
+
+    /**
+     * Add the watermark
+     *
+     */
+    public function apply()
+    {
+        /* Determine placement on image */
+        switch ($this->_params['valign']) {
+        case 'bottom':
+            $v = 'south';
+            break;
+        case 'center':
+            $v = 'center';
+            break;
+        default:
+            $v = 'north';
+        }
+
+        switch ($this->_params['halign']) {
+        case 'right':
+            $h = 'east';
+            break;
+        case 'center':
+            $h = 'center';
+            break;
+        default:
+            $h = 'west';
+
+        }
+        if (($v == 'center' && $h != 'center') ||
+            ($v == 'center' && $h == 'center')) {
+            $gravity = $h;
+        } elseif ($h == 'center' && $v != 'center') {
+            $gravity = $v;
+        } else {
+            $gravity = $v . $h;
+        }
+        /* Determine font point size */
+        $point = $this->_image->getFontSize($this->_params['fontsize']);
+        $this->_image->raw();
+        $this->_image->addPostSrcOperation(' -font ' . $this->_params['font'] . ' -pointsize ' . $point . ' \( +clone -resize 1x1 -fx 1-intensity -threshold 50% -scale 32x32 -write mpr:color +delete \) -tile mpr:color -gravity ' . $gravity . ' -annotate +20+10 "' . $this->_params['text'] . '"');
+        $this->_image->raw();
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Exception.php b/framework/Image/lib/Horde/Image/Exception.php
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/framework/Image/lib/Horde/Image/Gd.php b/framework/Image/lib/Horde/Image/Gd.php
new file mode 100644 (file)
index 0000000..e2ea5a0
--- /dev/null
@@ -0,0 +1,971 @@
+<?php
+/**
+ * This class implements the Horde_Image:: API for the PHP GD
+ * extension. It mainly provides some utility functions, such as the
+ * ability to make pixels, for now.
+ *
+ * Copyright 2002-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Gd extends Horde_Image
+{
+
+    /**
+     * Capabilites of this driver.
+     *
+     * @var array
+     */
+    protected $_capabilities = array('resize',
+                                     'crop',
+                                     'rotate',
+                                     'flip',
+                                     'mirror',
+                                     'grayscale',
+                                     'sepia',
+                                     'yellowize',
+                                     'canvas');
+
+    /**
+     * GD Image resource for the current image data.
+     *
+     * @TODO: Having this protected probably breaks effects
+     * @var resource
+     */
+    protected $_im;
+
+    /**
+     * Const'r
+     *
+     * @param $params
+     *
+     * @return Horde_Image_gd
+     */
+    public function __construct($params, $context = array())
+    {
+        parent::__construct($params, $context);
+        if (!empty($params['width'])) {
+            $this->_im = $this->create($this->_width, $this->_height);
+            if (is_a($this->_im, 'PEAR_Error')) {
+                return $this->_im;
+            }
+            if (is_resource($this->_im)) {
+                $this->call('imageFill', array($this->_im, 0, 0, $this->_allocateColor($this->_background)));
+            }
+        }
+    }
+
+    public function __get($property)
+    {
+        switch ($property) {
+        case '_im':
+             return $this->_im;
+        }
+    }
+
+    /**
+     * Display the current image.
+     */
+    public function display()
+    {
+        $this->headers();
+
+        return $this->call('image' . $this->_type, array($this->_im));
+    }
+
+    /**
+     * Returns the raw data for this image.
+     *
+     * @param boolean $convert (ignored)
+     *
+     * @return string  The raw image data.
+     */
+    public function raw($convert = false)
+    {
+        if (!is_resource($this->_im)) {
+            return '';
+        }
+
+        return Util::bufferOutput('image' . $this->_type, $this->_im);
+    }
+
+    /**
+     * Reset the image data.
+     */
+    public function reset()
+    {
+        parent::reset();
+        if (is_resource($this->_im)) {
+            return $this->call('imageDestroy', array($this->_im));
+        }
+
+        return true;
+    }
+
+    /**
+     * Get the height and width of the current image.
+     *
+     * @return array  An hash with 'width' containing the width,
+     *                'height' containing the height of the image.
+     */
+    public function getDimensions()
+    {
+        if (is_a($this->_im, 'PEAR_Error')) {
+            return $this->_im;
+        } elseif (is_resource($this->_im) && $this->_width == 0 && $this->_height ==0) {
+            $this->_width = $this->call('imageSX', array($this->_im));
+            $this->_height = $this->call('imageSY', array($this->_im));
+            return array('width' => $this->_width,
+                         'height' => $this->_height);
+        } else {
+            return array('width' => $this->_width,
+                         'height' => $this->_height);
+        }
+    }
+
+    /**
+     * Creates a color that can be accessed in this object. When a
+     * color is set, the integer resource of it is returned.
+     *
+     * @param string $name  The name of the color.
+     * @param int $alpha    Alpha transparency (0 - 127)
+     *
+     * @return integer  The resource of the color that can be passed to GD.
+     */
+    private function _allocateColor($name, $alpha = 0)
+    {
+        static $colors = array();
+
+        if (empty($colors[$name])) {
+            list($r, $g, $b) = self::getRGB($name);
+            $colors[$name] = $this->call('imageColorAllocateAlpha', array($this->_im, $r, $g, $b, $alpha));
+        }
+
+        return $colors[$name];
+    }
+
+    /**
+     *
+     *
+     * @param $font
+     * @return unknown_type
+     */
+    private function _getFont($font)
+    {
+        switch ($font) {
+        case 'tiny':
+            return 1;
+
+        case 'medium':
+            return 3;
+
+        case 'large':
+            return 4;
+
+        case 'giant':
+            return 5;
+
+        case 'small':
+        default:
+            return 2;
+        }
+    }
+
+    /**
+     * Load the image data from a string.
+     *
+     * @param string $id          An arbitrary id for the image.
+     * @param string $image_data  The data to use for the image.
+     */
+    public function loadString($id, $image_data)
+    {
+        if ($id != $this->_id) {
+            if ($this->_im) {
+                if (is_a($result = $this->reset(), 'PEAR_Error')) {
+                    return $result;
+                }
+            }
+            $this->_im = $this->call('imageCreateFromString', array($image_data));
+            $this->_id = $id;
+            if (is_a($this->_im, 'PEAR_Error')) {
+                return $this->_im;
+            }
+        }
+    }
+
+    /**
+     * Load the image data from a file.
+     *
+     * @param string $filename  The full path and filename to the file to load
+     *                          the image data from. The filename will also be
+     *                          used for the image id.
+     *
+     * @return mixed  true on success | PEAR Error if file does not exist or
+     *                could not be loaded.
+     */
+    public function loadFile($filename)
+    {
+        if (is_a($result = $this->reset(), 'PEAR_Error')) {
+            return $result;
+        }
+
+        if (is_a($info = $this->call('getimagesize', array($filename)), 'PEAR_Error')) {
+            return $info;
+        }
+
+        if (is_array($info)) {
+            switch ($info[2]) {
+            case 1:
+                if (function_exists('imagecreatefromgif')) {
+                    $this->_im = $this->call('imagecreatefromgif', array($filename));
+                }
+                break;
+            case 2:
+                $this->_im = $this->call('imagecreatefromjpeg', array($filename));
+                break;
+            case 3:
+                $this->_im = $this->call('imagecreatefrompng', array($filename));
+                break;
+            case 15:
+                if (function_exists('imagecreatefromgwbmp')) {
+                    $this->_im = $this->call('imagecreatefromgwbmp', array($filename));
+                }
+                break;
+            case 16:
+                $this->_im = $this->call('imagecreatefromxbm', array($filename));
+                break;
+            }
+        }
+
+        if (is_a($this->_im, 'PEAR_Error')) {
+            return $this->_im;
+        }
+
+        if (is_resource($this->_im)) {
+            return true;
+        }
+
+        $result = parent::loadFile($filename);
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+
+        return $this->_im = $this->call('imageCreateFromString', array($this->_data));
+    }
+
+    /**
+     * Resize the current image.
+     *
+     * @param integer $width      The new width.
+     * @param integer $height     The new height.
+     * @param boolean $ratio      Maintain original aspect ratio.
+     *
+     * @return PEAR_Error on failure
+     */
+    public function resize($width, $height, $ratio = true)
+    {
+        /* Abort if we're asked to divide by zero, truncate the image
+         * completely in either direction, or there is no image data.
+         * @TODO: This should throw an exception
+         */
+        if (!$width || !$height || !is_resource($this->_im)) {
+            return;
+        }
+
+        if ($ratio) {
+            if ($width / $height > $this->call('imageSX', array($this->_im)) / $this->call('imageSY', array($this->_im))) {
+                $width = $height * $this->call('imageSX', array($this->_im)) / $this->call('imageSY', array($this->_im));
+            } else {
+                $height = $width * $this->call('imageSY', array($this->_im)) / $this->call('imageSX', array($this->_im));
+            }
+        }
+
+        $im = $this->_im;
+        $this->_im = $this->create($width, $height);
+
+        /* Reset geometry since it will change */
+        $this->_width = 0;
+        $this->_height = 0;
+
+        if (is_a($this->_im, 'PEAR_Error')) {
+            return $this->_im;
+        }
+        if (is_a($result = $this->call('imageFill', array($this->_im, 0, 0, $this->call('imageColorAllocate', array($this->_im, 255, 255, 255)))), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($this->call('imageCopyResampled', array($this->_im, $im, 0, 0, 0, 0, $width, $height, $this->call('imageSX', array($im)), $this->call('imageSY', array($im)))), 'PEAR_Error')) {
+            return $this->call('imageCopyResized', array($this->_im, $im, 0, 0, 0, 0, $width, $height, $this->call('imageSX', array($im)), $this->call('imageSY', array($im))));
+        }
+    }
+
+    /**
+     * Crop the current image.
+     *
+     * @param integer $x1  The top left corner of the cropped image.
+     * @param integer $y1  The top right corner of the cropped image.
+     * @param integer $x2  The bottom left corner of the cropped image.
+     * @param integer $y2  The bottom right corner of the cropped image.
+     */
+    public function crop($x1, $y1, $x2, $y2)
+    {
+        $im = $this->_im;
+        $this->_im = $this->create($x2 - $x1, $y2 - $y1);
+        if (is_a($this->_im, 'PEAR_Error')) {
+            return $this->_im;
+        }
+        $this->_width = 0;
+        $this->_height = 0;
+        return $this->call('imageCopy', array($this->_im, $im, 0, 0, $x1, $y1, $x2 - $x1, $y2 - $y1));
+    }
+
+    /**
+     * Rotate the current image.
+     *
+     * @param integer $angle       The angle to rotate the image by,
+     *                             in the clockwise direction
+     * @param integer $background  The background color to fill any triangles
+     */
+    public function rotate($angle, $background = 'white')
+    {
+        $background = $this->_allocateColor($background);
+        if (is_a($background, 'PEAR_Error')) {
+            return $background;
+        }
+
+        $this->_width = 0;
+        $this->_height = 0;
+
+        switch ($angle) {
+        case '90':
+            $x = $this->call('imageSX', array($this->_im));
+            $y = $this->call('imageSY', array($this->_im));
+            $xymax = max($x, $y);
+
+            $im = $this->create($xymax, $xymax);
+            if (is_a($im, 'PEAR_Error')) {
+                return $im;
+            }
+            if (is_a($result = $this->call('imageCopy', array($im, $this->_im, 0, 0, 0, 0, $x, $y)), 'PEAR_Error')) {
+                return $result;
+            }
+            $im = $this->call('imageRotate', array($im, 270, $background));
+            if (is_a($im, 'PEAR_Error')) {
+                return $im;
+            }
+            $this->_im = $im;
+            $im = $this->create($y, $x);
+            if (is_a($im, 'PEAR_Error')) {
+                return $im;
+            }
+            if ($x < $y) {
+                if (is_a($result = $this->call('imageCopy', array($im, $this->_im, 0, 0, 0, 0, $xymax, $xymax)), 'PEAR_Error')) {
+                    return $result;
+                }
+            } elseif ($x > $y) {
+                if (is_a($result = $this->call('imageCopy', array($im, $this->_im, 0, 0, $xymax - $y, $xymax - $x, $xymax, $xymax)), 'PEAR_Error')) {
+                    return $result;
+                }
+            }
+            $this->_im = $im;
+            break;
+
+        default:
+            $this->_im = $this->call('imageRotate', array($this->_im, 360 - $angle, $background));
+            if (is_a($this->_im, 'PEAR_Error')) {
+                return $this->_im;
+            }
+            break;
+        }
+    }
+
+    /**
+     * Flip the current image.
+     */
+    public function flip()
+    {
+        $x = $this->call('imageSX', array($this->_im));
+        $y = $this->call('imageSY', array($this->_im));
+
+        $im = $this->create($x, $y);
+        if (is_a($im, 'PEAR_Error')) {
+            return $im;
+        }
+        for ($curY = 0; $curY < $y; $curY++) {
+            if (is_a($result = $this->call('imageCopy', array($im, $this->_im, 0, $y - ($curY + 1), 0, $curY, $x, 1)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        $this->_im = $im;
+    }
+
+    /**
+     * Mirror the current image.
+     */
+    public function mirror()
+    {
+        $x = $this->call('imageSX', array($this->_im));
+        $y = $this->call('imageSY', array($this->_im));
+
+        $im = $this->create($x, $y);
+        if (is_a($im, 'PEAR_Error')) {
+            return $im;
+        }
+        for ($curX = 0; $curX < $x; $curX++) {
+            if (is_a($result = $this->call('imageCopy', array($im, $this->_im, $x - ($curX + 1), 0, $curX, 0, 1, $y)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        $this->_im = $im;
+    }
+
+    /**
+     * Convert the current image to grayscale.
+     */
+    public function grayscale()
+    {
+        $rateR = .229;
+        $rateG = .587;
+        $rateB = .114;
+        $whiteness = 3;
+
+        if ($this->call('imageIsTrueColor', array($this->_im)) === true) {
+            if (is_a($result = $this->call('imageTrueColorToPalette', array($this->_im, true, 256)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        $colors = min(256, $this->call('imageColorsTotal', array($this->_im)));
+        for ($x = 0; $x < $colors; $x++) {
+            $src = $this->call('imageColorsForIndex', array($this->_im, $x));
+            if (is_a($src, 'PEAR_Error')) {
+                return $src;
+            }
+            $new = min(255, abs($src['red'] * $rateR + $src['green'] * $rateG + $src['blue'] * $rateB) + $whiteness);
+            if (is_a($result = $this->call('imageColorSet', array($this->_im, $x, $new, $new, $new)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Sepia filter.
+     *
+     * Basically turns the image to grayscale and then adds some
+     * defined tint on it (R += 30, G += 43, B += -23) so it will
+     * appear to be a very old picture.
+     *
+     * @param integer $threshold  (Ignored in GD driver for now)
+     */
+    public function sepia($threshold = 85)
+    {
+        $tintR = 80;
+        $tintG = 43;
+        $tintB = -23;
+        $rateR = .229;
+        $rateG = .587;
+        $rateB = .114;
+        $whiteness = 3;
+
+        if ($this->call('imageIsTrueColor', array($this->_im)) === true) {
+            if (is_a($result = $this->call('imageTrueColorToPalette', array($this->_im, true, 256)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        $colors = max(256, $this->call('imageColorsTotal', array($this->_im)));
+        for ($x = 0; $x < $colors; $x++) {
+            $src = $this->call('imageColorsForIndex', array($this->_im, $x));
+            if (is_a($src, 'PEAR_Error')) {
+                return $src;
+            }
+            $new = min(255, abs($src['red'] * $rateR + $src['green'] * $rateG + $src['blue'] * $rateB) + $whiteness);
+            $r = min(255, $new + $tintR);
+            $g = min(255, $new + $tintG);
+            $b = min(255, $new + $tintB);
+            if (is_a($result = $this->call('imageColorSet', array($this->_im, $x, $r, $g, $b)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Yellowize filter.
+     *
+     * Adds a layer of yellow that can be transparent or solid. If
+     * $intensityA is 255 the image will be 0% transparent (solid).
+     *
+     * @param integer $intensityY  How strong should the yellow (red and green) be? (0-255)
+     * @param integer $intensityB  How weak should the blue be? (>= 2, in the positive limit it will be make BLUE 0)
+     */
+    public function yellowize($intensityY = 50, $intensityB = 3)
+    {
+        if ($this->call('imageIsTrueColor', array($this->_im)) === true) {
+            if (is_a($result = $this->call('imageTrueColorToPalette', array($this->_im, true, 256)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        $colors = max(256, $this->call('imageColorsTotal', array($this->_im)));
+        for ($x = 0; $x < $colors; $x++) {
+            $src = $this->call('imageColorsForIndex', array($this->_im, $x));
+            if (is_a($src, 'PEAR_Error')) {
+                return $src;
+            }
+            $r = min($src['red'] + $intensityY, 255);
+            $g = min($src['green'] + $intensityY, 255);
+            $b = max(($r + $g) / max($intensityB, 2), 0);
+            if (is_a($result = $this->call('imageColorSet', array($this->_im, $x, $r, $g, $b)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Draws a text string on the image in a specified location, with
+     * the specified style information.
+     *
+     * @param string  $string     The text to draw.
+     * @param integer $x          The left x coordinate of the start of the
+     *                            text string.
+     * @param integer $y          The top y coordinate of the start of the text
+     *                            string.
+     * @param string  $font       The font identifier you want to use for the
+     *                            text (ignored for GD - font determined by
+     *                            $fontsize).
+     * @param string  $color      The color that you want the text displayed in.
+     * @param integer $direction  An integer that specifies the orientation of
+     *                            the text.
+     * @param string  $fontsize   The font (size) to use.
+     *
+     * @return @TODO
+     */
+    public function text($string, $x, $y, $font = 'monospace', $color = 'black', $direction = 0, $fontsize = 'small')
+    {
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+        $f = $this->_getFont($fontsize);
+        switch ($direction) {
+        case -90:
+        case 270:
+            $result = $this->call('imageStringUp', array($this->_im, $f, $x, $y, $string, $c));
+            break;
+
+        case 0:
+        default:
+            $result = $this->call('imageString', array($this->_im, $f, $x, $y, $string, $c));
+        }
+
+        return $result;
+    }
+
+    /**
+     * Draw a circle.
+     *
+     * @param integer $x     The x co-ordinate of the centre.
+     * @param integer $y     The y co-ordinate of the centre.
+     * @param integer $r     The radius of the circle.
+     * @param string $color  The line color of the circle.
+     * @param string $fill   The color to fill the circle.
+     */
+    public function circle($x, $y, $r, $color, $fill = null)
+    {
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+        if (is_null($fill)) {
+            $result = $this->call('imageEllipse', array($this->_im, $x, $y, $r * 2, $r * 2, $c));
+        } else {
+            if ($fill !== $color) {
+                $fillColor = $this->_allocateColor($fill);
+                if (is_a($fillColor, 'PEAR_Error')) {
+                    return $fillColor;
+                }
+                if (is_a($result = $this->call('imageFilledEllipse', array($this->_im, $x, $y, $r * 2, $r * 2, $fillColor)), 'PEAR_Error')) {
+                    return $result;
+                }
+                $result = $this->call('imageEllipse', array($this->_im, $x, $y, $r * 2, $r * 2, $c));
+            } else {
+                $result = $this->call('imageFilledEllipse', array($this->_im, $x, $y, $r * 2, $r * 2, $c));
+            }
+        }
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+    }
+
+    /**
+     * Draw a polygon based on a set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the polygon with.
+     * @param string $fill     The color to fill the polygon.
+     */
+    public function polygon($verts, $color, $fill = 'none')
+    {
+        $vertices = array();
+        foreach ($verts as $vert) {
+            $vertices[] = $vert['x'];
+            $vertices[] = $vert['y'];
+        }
+
+        if ($fill != 'none') {
+            $f = $this->_allocateColor($fill);
+            if (is_a($f, 'PEAR_Error')) {
+                return $f;
+            }
+            if (is_a($result = $this->call('imageFilledPolygon', array($this->_im, $vertices, count($verts), $f)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        if ($fill == 'none' || $fill != $color) {
+            $c = $this->_allocateColor($color);
+            if (is_a($c, 'PEAR_Error')) {
+                return $c;
+            }
+            if (is_a($result = $this->call('imagePolygon', array($this->_im, $vertices, count($verts), $c)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rectangle with.
+     */
+    public function rectangle($x, $y, $width, $height, $color = 'black', $fill = 'none')
+    {
+        if ($fill != 'none') {
+            $f = $this->_allocateColor($fill);
+            if (is_a($f, 'PEAR_Error')) {
+                return $f;
+            }
+            if (is_a($result = $this->call('imageFilledRectangle', array($this->_im, $x, $y, $x + $width, $y + $height, $f)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+
+        if ($fill == 'none' || $fill != $color) {
+            $c = $this->_allocateColor($color);
+            if (is_a($c, 'PEAR_Error')) {
+                return $c;
+            }
+            if (is_a($result = $this->call('imageRectangle', array($this->_im, $x, $y, $x + $width, $y + $height, $c)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Draw a rounded rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param integer $round   The width of the corner rounding.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rounded rectangle with.
+     */
+    public function roundedRectangle($x, $y, $width, $height, $round, $color = 'black', $fill = 'none')
+    {
+        if ($round <= 0) {
+            // Optimize out any calls with no corner rounding.
+            return $this->rectangle($x, $y, $width, $height, $color, $fill);
+        }
+
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+
+        // Set corner points to avoid lots of redundant math.
+        $x1 = $x + $round;
+        $y1 = $y + $round;
+
+        $x2 = $x + $width - $round;
+        $y2 = $y + $round;
+
+        $x3 = $x + $width - $round;
+        $y3 = $y + $height - $round;
+
+        $x4 = $x + $round;
+        $y4 = $y + $height - $round;
+
+        $r = $round * 2;
+
+        // Calculate the upper left arc.
+        $p1 = self::_arcPoints($round, 180, 225);
+        $p2 = self::_arcPoints($round, 225, 270);
+
+        // Calculate the upper right arc.
+        $p3 = self::_arcPoints($round, 270, 315);
+        $p4 = self::_arcPoints($round, 315, 360);
+
+        // Calculate the lower right arc.
+        $p5 = self::_arcPoints($round, 0, 45);
+        $p6 = self::_arcPoints($round, 45, 90);
+
+        // Calculate the lower left arc.
+        $p7 = self::_arcPoints($round, 90, 135);
+        $p8 = self::_arcPoints($round, 135, 180);
+
+        // Draw the corners - upper left, upper right, lower right,
+        // lower left.
+        if (is_a($result = $this->call('imageArc', array($this->_im, $x1, $y1, $r, $r, 180, 270, $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageArc', array($this->_im, $x2, $y2, $r, $r, 270, 360, $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageArc', array($this->_im, $x3, $y3, $r, $r, 0, 90, $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageArc', array($this->_im, $x4, $y4, $r, $r, 90, 180, $c)), 'PEAR_Error')) {
+            return $result;
+        }
+
+        // Draw the connecting sides - top, right, bottom, left.
+        if (is_a($result = $this->call('imageLine', array($this->_im, $x1 + $p2['x2'], $y1 + $p2['y2'], $x2 + $p3['x1'], $y2 + $p3['y1'], $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageLine', array($this->_im, $x2 + $p4['x2'], $y2 + $p4['y2'], $x3 + $p5['x1'], $y3 + $p5['y1'], $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageLine', array($this->_im, $x3 + $p6['x2'], $y3 + $p6['y2'], $x4 + $p7['x1'], $y4 + $p7['y1'], $c)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageLine', array($this->_im, $x4 + $p8['x2'], $y4 + $p8['y2'], $x1 + $p1['x1'], $y1 + $p1['y1'], $c)), 'PEAR_Error')) {
+            return $result;
+        }
+
+        if ($fill != 'none') {
+            $f = $this->_allocateColor($fill);
+            if (is_a($f, 'PEAR_Error')) {
+                return $f;
+            }
+            if (is_a($result = $this->call('imageFillToBorder', array($this->_im, $x + ($width / 2), $y + ($height / 2), $c, $f)), 'PEAR_Error')) {
+                return $result;
+            }
+        }
+    }
+
+    /**
+     * Draw a line.
+     *
+     * @param integer $x0    The x co-ordinate of the start.
+     * @param integer $y0    The y co-ordinate of the start.
+     * @param integer $x1    The x co-ordinate of the end.
+     * @param integer $y1    The y co-ordinate of the end.
+     * @param string $color  The line color.
+     * @param string $width  The width of the line.
+     */
+    public function line($x1, $y1, $x2, $y2, $color = 'black', $width = 1)
+    {
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+
+        // Don't need to do anything special for single-width lines.
+        if ($width == 1) {
+            $result = $this->call('imageLine', array($this->_im, $x1, $y1, $x2, $y2, $c));
+        } elseif ($x1 == $x2) {
+            // For vertical lines, we can just draw a vertical
+            // rectangle.
+            $left = $x1 - floor(($width - 1) / 2);
+            $right = $x1 + floor($width / 2);
+            $result = $this->call('imageFilledRectangle', array($this->_im, $left, $y1, $right, $y2, $c));
+        } elseif ($y1 == $y2) {
+            // For horizontal lines, we can just draw a horizontal
+            // filled rectangle.
+            $top = $y1 - floor($width / 2);
+            $bottom = $y1 + floor(($width - 1) / 2);
+            $result = $this->call('imageFilledRectangle', array($this->_im, $x1, $top, $x2, $bottom, $c));
+        } else {
+            // Angled lines.
+
+            // Make sure that the end points of the line are
+            // perpendicular to the line itself.
+            $a = atan2($y1 - $y2, $x2 - $x1);
+            $dx = (sin($a) * $width / 2);
+            $dy = (cos($a) * $width / 2);
+
+            $verts = array($x2 + $dx, $y2 + $dy, $x2 - $dx, $y2 - $dy, $x1 - $dx, $y1 - $dy, $x1 + $dx, $y1 + $dy);
+            $result = $this->call('imageFilledPolygon', array($this->_im, $verts, count($verts) / 2, $c));
+        }
+
+        return $result;
+    }
+
+    /**
+     * Draw a dashed line.
+     *
+     * @param integer $x0           The x co-ordinate of the start.
+     * @param integer $y0           The y co-ordinate of the start.
+     * @param integer $x1           The x co-ordinate of the end.
+     * @param integer $y1           The y co-ordinate of the end.
+     * @param string $color         The line color.
+     * @param string $width         The width of the line.
+     * @param integer $dash_length  The length of a dash on the dashed line
+     * @param integer $dash_space   The length of a space in the dashed line
+     */
+    public function dashedLine($x0, $y0, $x1, $y1, $color = 'black', $width = 1, $dash_length = 2, $dash_space = 2)
+    {
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+        $w = $this->_allocateColor('white');
+        if (is_a($w, 'PEAR_Error')) {
+            return $w;
+        }
+
+        // Set up the style array according to the $dash_* parameters.
+        $style = array();
+        for ($i = 0; $i < $dash_length; $i++) {
+            $style[] = $c;
+        }
+        for ($i = 0; $i < $dash_space; $i++) {
+            $style[] = $w;
+        }
+
+        if (is_a($result = $this->call('imageSetStyle', array($this->_im, $style)), 'PEAR_Error')) {
+            return $result;
+        }
+        if (is_a($result = $this->call('imageSetThickness', array($this->_im, $width)), 'PEAR_Error')) {
+            return $result;
+        }
+        return $this->call('imageLine', array($this->_im, $x0, $y0, $x1, $y1, IMG_COLOR_STYLED));
+    }
+
+    /**
+     * Draw a polyline (a non-closed, non-filled polygon) based on a
+     * set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the line with.
+     * @param string $width    The width of the line.
+     */
+    public function polyline($verts, $color, $width = 1)
+    {
+        $first = true;
+        foreach ($verts as $vert) {
+            if (!$first) {
+                if (is_a($result = $this->line($lastX, $lastY, $vert['x'], $vert['y'], $color, $width), 'PEAR_Error')) {
+                    return $result;
+                }
+            } else {
+                $first = false;
+            }
+            $lastX = $vert['x'];
+            $lastY = $vert['y'];
+        }
+    }
+
+    /**
+     * Draw an arc.
+     *
+     * @param integer $x      The x co-ordinate of the centre.
+     * @param integer $y      The y co-ordinate of the centre.
+     * @param integer $r      The radius of the arc.
+     * @param integer $start  The start angle of the arc.
+     * @param integer $end    The end angle of the arc.
+     * @param string  $color  The line color of the arc.
+     * @param string  $fill   The fill color of the arc (defaults to none).
+     */
+    public function arc($x, $y, $r, $start, $end, $color = 'black', $fill = null)
+    {
+        $c = $this->_allocateColor($color);
+        if (is_a($c, 'PEAR_Error')) {
+            return $c;
+        }
+        if (is_null($fill)) {
+            $result = $this->call('imageArc', array($this->_im, $x, $y, $r * 2, $r * 2, $start, $end, $c));
+        } else {
+            if ($fill !== $color) {
+                $f = $this->_allocateColor($fill);
+                if (is_a($f, 'PEAR_Error')) {
+                    return $f;
+                }
+                if (is_a($result = $this->call('imageFilledArc', array($this->_im, $x, $y, $r * 2, $r * 2, $start, $end, $f, IMG_ARC_PIE)), 'PEAR_Error')) {
+                    return $result;
+                }
+                $result = $this->call('imageFilledArc', array($this->_im, $x, $y, $r * 2, $r * 2, $start, $end, $c, IMG_ARC_EDGED | IMG_ARC_NOFILL));
+            } else {
+                $result = $this->call('imageFilledArc', array($this->_im, $x, $y, $r * 2, $r * 2, $start, $end, $c, IMG_ARC_PIE));
+            }
+        }
+        return $result;
+    }
+
+    /**
+     * Creates an image of the given size.
+     * If possible the function returns a true color image.
+     *
+     * @param integer $width   The image width.
+     * @param integer $height  The image height.
+     *
+     * @return resource|object PEAR Error  The image handler or a PEAR_Error
+     *                                     on error.
+     */
+    public function create($width, $height)
+    {
+        $result = $this->call('imageCreateTrueColor', array($width, $height));
+        if (!is_resource($result)) {
+            // @TODO: Throw an exception here instead.
+            $result = PEAR::raiseError(_("Could not create image."));
+        }
+
+        return $result;
+    }
+
+    /**
+     * Wraps a call to a function of the gd extension.
+     * If the call produces an error, a PEAR_Error is returned, the function
+     * result otherwise.
+     *
+     * @param string $function  The name of the function to wrap.
+     * @param array $params     An array with all parameters for that function.
+     *
+     * @return mixed  Either the function result or a PEAR_Error if an error
+     *                occured when executing the function.
+     */
+    public function call($function, $params = null)
+    {
+        unset($php_errormsg);
+        $track = ini_set('track_errors', 1);
+        $error_mask = E_ALL & ~E_WARNING & ~E_NOTICE;
+        error_reporting($error_mask);
+        $result = call_user_func_array($function, $params);
+        if ($track !== false) {
+            ini_set('track_errors', $track);
+        }
+        error_reporting($GLOBALS['conf']['debug_level']);
+        if (!empty($php_errormsg)) {
+            $error_msg = $php_errormsg;
+            require_once 'PEAR.php';
+            $result = PEAR::raiseError($function . ': ' . $error_msg);
+        }
+        return $result;
+    }
+
+}
diff --git a/framework/Image/lib/Horde/Image/Im.php b/framework/Image/lib/Horde/Image/Im.php
new file mode 100644 (file)
index 0000000..0ad8c16
--- /dev/null
@@ -0,0 +1,767 @@
+<?php
+/**
+ * This class implements the Horde_Image:: API for ImageMagick.
+ *
+ * Copyright 2002-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @author  Mike Cochrane <mike@graftonhall.co.nz>
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Im extends Horde_Image
+{
+    /**
+     * Capabilites of this driver.
+     *
+     * @var array
+     */
+    protected $_capabilities = array('resize',
+                                     'crop',
+                                     'rotate',
+                                     'grayscale',
+                                     'flip',
+                                     'mirror',
+                                     'sepia',
+                                     'canvas');
+
+    /**
+     * Operations to be performed before the source filename is specified on the
+     * command line.
+     *
+     * @var array
+     */
+    protected $_operations = array();
+
+    /**
+     * Operations to be added after the source filename is specified on the
+     * command line.
+     *
+     * @var array
+     */
+    protected $_postSrcOperations = array();
+
+    /**
+     * Reference to an Horde_Image_ImagickProxy object.
+     *
+     * @TODO: This needs to be public since some of the Effects need to
+     *        access this and possibly null it out. This will be resolved
+     *        when Imagick is pulled out into it's own driver.
+     *
+     * @var Imagick
+     */
+    public $_imagick = null;
+
+    /**
+     * An array of temporary filenames that need to be unlinked at the end of
+     * processing. Use addFileToClean() from client code (Effects) to add files
+     * to this array.
+     *
+     * @var array
+     */
+    protected $_toClean = array();
+
+    /**
+     * Path to the convert binary
+     *
+     * @string
+     */
+    protected $_convert = '';
+
+    /**
+     * Constructor.
+     */
+    public function __construct($params, $context = array())
+    {
+        parent::__construct($params, $context);
+
+        if (empty($context['convert'])) {
+            throw new InvalidArgumentException('A path to the convert binary is required.');
+        }
+        $this->_convert = $context['convert'];
+
+        // TODO: Will be breaking out Imagick into it's own driver.
+
+        // Imagick library doesn't play nice with outputting data for 0x0
+        // images, so use 1x1 for our default if needed.
+        if (Util::loadExtension('imagick')) {
+            ini_set('imagick.locale_fix', 1);
+            $this->_width = max(array($this->_width, 1));
+            $this->_height = max(array($this->_height, 1));
+            // Use a proxy for the Imagick calls to keep exception catching
+            // code out of PHP4 compliant code.
+            $this->_imagick = new Horde_Image_ImagickProxy($this->_width,
+                                                           $this->_height,
+                                                           $this->_background,
+                                                           $this->_type);
+            // Yea, it's wasteful to create the proxy (which creates a blank
+            // image) then overwrite it if we're passing in an image, but this
+            // will be fixed in Horde 4 when imagick is broken out into it's own
+            // proper driver.
+            if (!empty($params['filename'])) {
+                $this->loadFile($params['filename']);
+            } elseif(!empty($params['data'])) {
+                $this->loadString(md5($params['data']), $params['data']);
+            } else {
+                $this->_data = $this->_imagick->getImageBlob();
+            }
+
+            $this->_imagick->setImageFormat($this->_type);
+        } else {
+            if (!empty($params['filename'])) {
+                $this->loadFile($params['filename']);
+            } elseif (!empty($params['data'])) {
+                $this->loadString(md5($params['data']), $params['data']);
+            } else {
+                $cmd = "-size {$this->_width}x{$this->_height} xc:{$this->_background} +profile \"*\" {$this->_type}:__FILEOUT__";
+                $this->executeConvertCmd($cmd);
+            }
+        }
+    }
+
+//    /**
+//     * Load the image data from a string. Need to override this method
+//     * in order to load the imagick object if we need to.
+//     *
+//     * @TODO: This can be nuked when imagick is broken out.
+//     *
+//     * @param string $id          An arbitrary id for the image.
+//     * @param string $image_data  The data to use for the image.
+//     */
+//    public function loadString($id, $image_data)
+//    {
+//        parent::loadString($id, $image_data);
+//        if (!is_null($this->_imagick)) {
+//            $this->_imagick->clear();
+//            $this->_imagick->readImageBlob($image_data);
+//            $this->_imagick->setFormat($this->_type);
+//            $this->_imagick->setIteratorIndex(0);
+//        }
+//    }
+
+    /**
+     * Load the image data from a file. Need to override this method
+     * in order to load the imagick object if we need to.
+     *
+     * @TODO: Nuke when imagick is broken out.
+     *
+     * @param string $filename  The full path and filename to the file to load
+     *                          the image data from. The filename will also be
+     *                          used for the image id.
+     *
+     * @return mixed  PEAR Error if file does not exist or could not be loaded
+     *                otherwise NULL if successful or already loaded.
+     */
+    public function loadFile($filename)
+    {
+        parent::loadFile($filename);
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->clear();
+            $this->_imagick->readImageBlob($this->_data);
+            $this->_imagick->setIteratorIndex(0);
+        }
+    }
+
+    /**
+     * Returns the raw data for this image.
+     *
+     * @param boolean $convert  If true, the image data will be returned in the
+     *                          target format, even if no other image operations
+     *                          are present, otherwise, if no operations are
+     *                          present, the current raw data is returned
+     *                          unmodified.
+     *
+     * @return string  The raw image data.
+     */
+    public function raw($convert = false)
+    {
+        // Make sure _data is sync'd with imagick object
+        if (!is_null($this->_imagick)) {
+            $this->_data = $this->_imagick->getImageBlob();
+        }
+
+        if (!empty($this->_data)) {
+            // If there are no operations, and we already have data, don't
+            // bother writing out files, just return the current data.
+            if (!$convert &&
+                !count($this->_operations) &&
+                !count($this->_postSrcOperations)) {
+                return $this->_data;
+            }
+
+            $tmpin = $this->toFile($this->_data);
+        }
+
+        // Perform convert command if needed
+        if (count($this->_operations) || count($this->_postSrcOperations) || $convert) {
+            $tmpout = Util::getTempFile('img', false, $this->_tmpdir);
+            $command = $this->_convert . ' ' . implode(' ', $this->_operations)
+                . ' "' . $tmpin . '"\'[0]\' '
+                . implode(' ', $this->_postSrcOperations)
+                . ' +profile "*" ' . $this->_type . ':"' . $tmpout . '" 2>&1';
+            $this->_logDebug(sprintf("convert command executed by Horde_Image_im::raw(): %s", $command));
+            exec($command, $output, $retval);
+            if ($retval) {
+                $this->_logErr(sprintf("Error running command: %s"), $command . "\n" . implode("\n", $output));
+            }
+
+            /* Empty the operations queue */
+            $this->_operations = array();
+            $this->_postSrcOperations = array();
+
+            /* Load the result */
+            $this->_data = file_get_contents($tmpout);
+
+            // Keep imagick object in sync if we need to.
+            // @TODO: Might be able to stop doing this once all operations
+            // are doable through imagick api.
+            if (!is_null($this->_imagick)) {
+                $this->_imagick->clear();
+                $this->_imagick->readImageBlob($this->_data);
+            }
+        }
+
+        @unlink($tmpin);
+        @unlink($tmpout);
+
+        return $this->_data;
+    }
+
+    /**
+     * Reset the image data.
+     */
+    public function reset()
+    {
+        parent::reset();
+        $this->_operations = array();
+        $this->_postSrcOperations = array();
+        if (is_object($this->_imagick)) {
+            $this->_imagick->clear();
+        }
+        $this->_width = 0;
+        $this->_height = 0;
+    }
+
+    /**
+     * Resize the current image. This operation takes place immediately.
+     *
+     * @param integer $width        The new width.
+     * @param integer $height       The new height.
+     * @param boolean $ratio        Maintain original aspect ratio.
+     * @param boolean $keepProfile  Keep the image meta data.
+     */
+    public function resize($width, $height, $ratio = true, $keepProfile = false)
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->thumbnailImage($width, $height, $ratio);
+        } else {
+            $resWidth = $width * 2;
+            $resHeight = $height * 2;
+            $this->_operations[] = "-size {$resWidth}x{$resHeight}";
+            if ($ratio) {
+                $this->_postSrcOperations[] = (($keepProfile) ? "-resize" : "-thumbnail") . " {$width}x{$height}";
+            } else {
+                $this->_postSrcOperations[] = (($keepProfile) ? "-resize" : "-thumbnail") . " {$width}x{$height}!";
+            }
+        }
+        // Reset the width and height instance variables since after resize
+        // we don't know the *exact* dimensions yet (especially if we maintained
+        // aspect ratio.
+        // Refresh the data
+        $this->raw();
+        $this->_width = 0;
+        $this->_height = 0;
+    }
+
+    /**
+     * More efficient way of getting size if using imagick library.
+     * *ALWAYS* use getDimensions() to get image geometry...instance
+     * variables only cache geometry until it changes, then they go
+     * to zero.
+     *
+     */
+    public function getDimensions()
+    {
+        if (!is_null($this->_imagick)) {
+            if ($this->_height == 0 && $this->_width == 0) {
+                $size = $this->_imagick->getImageGeometry();
+                if (is_a($size, 'PEAR_Error')) {
+                    return $size;
+                }
+                $this->_height = $size['height'];
+                $this->_width = $size['width'];
+            }
+            return array('width' => $this->_width,
+                         'height' => $this->_height);
+        } else {
+            return parent::getDimensions();
+        }
+    }
+
+    /**
+     * Crop the current image.
+     *
+     * @param integer $x1  x for the top left corner
+     * @param integer $y1  y for the top left corner
+     * @param integer $x2  x for the bottom right corner of the cropped image.
+     * @param integer $y2  y for the bottom right corner of the cropped image.
+     */
+    public function crop($x1, $y1, $x2, $y2)
+    {
+        if (!is_null($this->_imagick)) {
+            $result = $this->_imagick->cropImage($x2 - $x1, $y2 - $y1, $x1, $y1);
+            $this->_imagick->setImagePage(0, 0, 0, 0);
+        } else {
+            $line = ($x2 - $x1) . 'x' . ($y2 - $y1) . '+' . $x1 . '+' . $y1;
+            $this->_operations[] = '-crop ' . $line . ' +repage';
+            $result = true;
+        }
+        // Reset width/height since these might change
+        $this->raw();
+        $this->_width = 0;
+        $this->_height = 0;
+
+        return $result;
+    }
+
+    /**
+     * Rotate the current image.
+     *
+     * @param integer $angle       The angle to rotate the image by,
+     *                             in the clockwise direction.
+     * @param integer $background  The background color to fill any triangles.
+     */
+    public function rotate($angle, $background = 'white')
+    {
+        if (!is_null($this->_imagick)) {
+            return $this->_imagick->rotateImage($background, $angle);
+        } else {
+            $this->raw();
+            $this->_operations[] = "-background $background -rotate {$angle}";
+            $this->raw();
+        }
+        // Reset width/height since these might have changed
+        $this->_width = 0;
+        $this->_height = 0;
+    }
+
+    /**
+     * Flip the current image.
+     */
+    public function flip()
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->flipImage();
+        } else {
+            $this->_operations[] = '-flip';
+        }
+    }
+
+    /**
+     * Mirror the current image.
+     */
+    public function mirror()
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->flopImage();
+        } else {
+            $this->_operations[] = '-flop';
+        }
+    }
+
+    /**
+     * Convert the current image to grayscale.
+     */
+    public function grayscale()
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->setImageColorSpace(constant('Imagick::COLORSPACE_GRAY'));
+        } else {
+            $this->_postSrcOperations[] = '-colorspace GRAY';
+        }
+    }
+
+    /**
+     * Sepia filter.
+     *
+     * @param integer $threshold  Extent of sepia effect.
+     */
+    public function sepia($threshold =  85)
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->sepiaToneImage($threshold);
+        } else {
+            $this->_operations[] = '-sepia-tone ' . $threshold . '%';
+        }
+    }
+
+     /**
+     * Draws a text string on the image in a specified location, with
+     * the specified style information.
+     *
+     * @TODO: Need to differentiate between the stroke (border) and the fill color,
+     *        but this is a BC break, since we were just not providing a border.
+     *
+     * @param string  $text       The text to draw.
+     * @param integer $x          The left x coordinate of the start of the text string.
+     * @param integer $y          The top y coordinate of the start of the text string.
+     * @param string  $font       The font identifier you want to use for the text.
+     * @param string  $color      The color that you want the text displayed in.
+     * @param integer $direction  An integer that specifies the orientation of the text.
+     * @param string  $fontsize   Size of the font (small, medium, large, giant)
+     */
+    public function text($string, $x, $y, $font = '', $color = 'black', $direction = 0, $fontsize = 'small')
+    {
+        if (!is_null($this->_imagick)) {
+            $fontsize = self::getFontSize($fontsize);
+
+            return $this->_imagick->text($string, $x, $y, $font, $color, $direction, $fontsize);
+        } else {
+            $string = addslashes('"' . $string . '"');
+            $fontsize = self::getFontSize($fontsize);
+            $this->_postSrcOperations[] = "-fill $color " . (!empty($font) ? "-font $font" : '') . " -pointsize $fontsize -gravity northwest -draw \"text $x,$y $string\" -fill none";
+        }
+    }
+
+    /**
+     * Draw a circle.
+     *
+     * @param integer $x     The x coordinate of the centre.
+     * @param integer $y     The y coordinate of the centre.
+     * @param integer $r     The radius of the circle.
+     * @param string $color  The line color of the circle.
+     * @param string $fill   The color to fill the circle.
+     */
+    public function circle($x, $y, $r, $color, $fill = 'none')
+    {
+        if (!is_null($this->_imagick)) {
+            return $this->_imagick->circle($x, $y, $r, $color, $fill);
+        } else {
+            $xMax = $x + $r;
+            $this->_postSrcOperations[] = "-stroke $color -fill $fill -draw \"circle $x,$y $xMax,$y\" -stroke none -fill none";
+        }
+    }
+
+    /**
+     * Draw a polygon based on a set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the polygon with.
+     * @param string $fill     The color to fill the polygon.
+     */
+    public function polygon($verts, $color, $fill = 'none')
+    {
+        // TODO: For now, use only convert since ::polygon is called from other
+        // methods that are convert-only for now.
+        //if (!is_null($this->_imagick)) {
+            //return $this->_imagick->polygon($verts, $color, $fill);
+        //} else {
+            $command = '';
+            foreach ($verts as $vert) {
+                $command .= sprintf(' %d,%d', $vert['x'], $vert['y']);
+            }
+            $this->_postSrcOperations[] = "-stroke $color -fill $fill -draw \"polygon $command\" -stroke none -fill none";
+        //}
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rectangle.
+     */
+    public function rectangle($x, $y, $width, $height, $color, $fill = 'none')
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->rectangle($x, $y, $width, $height, $color, $fill);
+        } else {
+            $xMax = $x + $width;
+            $yMax = $y + $height;
+            $this->_postSrcOperations[] = "-stroke $color -fill $fill -draw \"rectangle $x,$y $xMax,$yMax\" -stroke none -fill none";
+        }
+    }
+
+    /**
+     * Draw a rounded rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param integer $round   The width of the corner rounding.
+     * @param string  $color   The line color of the rectangle.
+     * @param string  $fill    The color to fill the rounded rectangle with.
+     */
+    public function roundedRectangle($x, $y, $width, $height, $round, $color, $fill)
+    {
+        if (!is_null($this->_imagick)) {
+            $this->_imagick->roundedRectangle($x, $y, $width, $height, $round, $color, $fill);
+        } else {
+            $x1 = $x + $width;
+            $y1 = $y + $height;
+            $this->_postSrcOperations[] = "-stroke $color -fill $fill -draw \"roundRectangle $x,$y $x1,$y1 $round,$round\" -stroke none -fill none";
+
+        }
+    }
+
+    /**
+     * Draw a line.
+     *
+     * @param integer $x0     The x coordinate of the start.
+     * @param integer $y0     The y coordinate of the start.
+     * @param integer $x1     The x coordinate of the end.
+     * @param integer $y1     The y coordinate of the end.
+     * @param string $color   The line color.
+     * @param string $width   The width of the line.
+     */
+    public function line($x0, $y0, $x1, $y1, $color = 'black', $width = 1)
+    {
+        if (!is_null($this->_imagick)) {
+            return $this->_imagick->line($x0, $y0, $x1, $y1, $color, $width);
+        } else {
+            $this->_operations[] = "-stroke $color -strokewidth $width -draw \"line $x0,$y0 $x1,$y1\"";
+        }
+    }
+
+    /**
+     * Draw a dashed line.
+     *
+     * @param integer $x0           The x co-ordinate of the start.
+     * @param integer $y0           The y co-ordinate of the start.
+     * @param integer $x1           The x co-ordinate of the end.
+     * @param integer $y1           The y co-ordinate of the end.
+     * @param string $color         The line color.
+     * @param string $width         The width of the line.
+     * @param integer $dash_length  The length of a dash on the dashed line
+     * @param integer $dash_space   The length of a space in the dashed line
+     */
+    public function dashedLine($x0, $y0, $x1, $y1, $color = 'black', $width = 1, $dash_length = 2, $dash_space = 2)
+    {
+        if (!is_null($this->_imagick)) {
+            return $this->_imagick->dashedLine($x0, $y0, $x1, $y1, $color,
+                                               $width, $dash_length,
+                                               $dash_space);
+        } else {
+            $this->_operations[] = "-stroke $color -strokewidth $width -draw \"line $x0,$y0 $x1,$y1\"";
+        }
+    }
+
+    /**
+     * Draw a polyline (a non-closed, non-filled polygon) based on a
+     * set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the line with.
+     * @param string $width    The width of the line.
+     */
+    public function polyline($verts, $color, $width = 1)
+    {
+        if (!is_null($this->_imagick)) {
+            return $this->_imagick->polyline($verts, $color, $width);
+        } else {
+            $command = '';
+            foreach ($verts as $vert) {
+                $command .= sprintf(' %d,%d', $vert['x'], $vert['y']);
+            }
+            $this->_operations[] = "-stroke $color -strokewidth $width -fill none -draw \"polyline $command\" -strokewidth 1 -stroke none -fill none";
+        }
+    }
+
+    /**
+     * Draw an arc.
+     *
+     * @param integer $x      The x coordinate of the centre.
+     * @param integer $y      The y coordinate of the centre.
+     * @param integer $r      The radius of the arc.
+     * @param integer $start  The start angle of the arc.
+     * @param integer $end    The end angle of the arc.
+     * @param string  $color  The line color of the arc.
+     * @param string  $fill   The fill color of the arc (defaults to none).
+     */
+    public function arc($x, $y, $r, $start, $end, $color = 'black', $fill = 'none')
+    {
+        // Split up arcs greater than 180 degrees into two pieces.
+        $this->_postSrcOperations[] = "-stroke $color -fill $fill";
+        $mid = round(($start + $end) / 2);
+        $x = round($x);
+        $y = round($y);
+        $r = round($r);
+        if ($mid > 90) {
+            $this->_postSrcOperations[] = "-draw \"ellipse $x,$y $r,$r $start,$mid\"";
+            $this->_postSrcOperations[] = "-draw \"ellipse $x,$y $r,$r $mid,$end\"";
+        } else {
+            $this->_postSrcOperations[] = "-draw \"ellipse $x,$y $r,$r $start,$end\"";
+        }
+
+        // If filled, draw the outline.
+        if (!empty($fill)) {
+            list($x1, $y1) = $this->_circlePoint($start, $r * 2);
+            list($x2, $y2) = $this->_circlePoint($mid, $r * 2);
+            list($x3, $y3) = $this->_circlePoint($end, $r * 2);
+
+            // This seems to result in slightly better placement of
+            // pie slices.
+            $x++;
+            $y++;
+
+            $verts = array(array('x' => $x + $x3, 'y' => $y + $y3),
+                           array('x' => $x, 'y' => $y),
+                           array('x' => $x + $x1, 'y' => $y + $y1));
+
+            if ($mid > 90) {
+                $verts1 = array(array('x' => $x + $x2, 'y' => $y + $y2),
+                                array('x' => $x, 'y' => $y),
+                                array('x' => $x + $x1, 'y' => $y + $y1));
+                $verts2 = array(array('x' => $x + $x3, 'y' => $y + $y3),
+                                array('x' => $x, 'y' => $y),
+                                array('x' => $x + $x2, 'y' => $y + $y2));
+
+                $this->polygon($verts1, $fill, $fill);
+                $this->polygon($verts2, $fill, $fill);
+            } else {
+                $this->polygon($verts, $fill, $fill);
+            }
+
+            $this->polyline($verts, $color);
+
+            $this->_postSrcOperations[] = '-stroke none -fill none';
+        }
+    }
+
+    public function applyEffects()
+    {
+        $this->raw();
+        foreach ($this->_toClean as $tempfile) {
+            @unlink($tempfile);
+        }
+    }
+
+    /**
+     * Method to execute a raw command directly in convert. Useful for executing
+     * more involved operations that may require multiple convert commands
+     * piped into each other for example. Really designed for use by im based
+     * Horde_Image_Effect objects..
+     *
+     * The input and output files are quoted and substituted for __FILEIN__ and
+     * __FILEOUT__ respectfully. In order to support piped convert commands, the
+     * path to the convert command is substitued for __CONVERT__ (but the
+     * initial convert command is added automatically).
+     *
+     * @param string $cmd    The command string, with substitutable tokens
+     * @param array $values  Any values that should be substituted for tokens.
+     *
+     * @return
+     */
+    public function executeConvertCmd($cmd, $values = array())
+    {
+        // First, get a temporary file for the input
+        if (strpos($cmd, '__FILEIN__') !== false) {
+            $tmpin = $this->toFile($this->_data);
+        } else {
+            $tmpin = '';
+        }
+
+        // Now an output file
+        $tmpout = Util::getTempFile('img', false, $this->_tmpdir);
+
+        // Substitue them in the cmd string
+        $cmd = str_replace(array('__FILEIN__', '__FILEOUT__', '__CONVERT__'),
+                           array('"' . $tmpin . '"', '"' . $tmpout . '"', $this->_convert),
+                           $cmd);
+
+        //TODO: See what else needs to be replaced.
+        $cmd = $this->_convert . ' ' . $cmd . ' 2>&1';
+
+        // Log it
+        $this->_logDebug(sprintf("convert command executed by Horde_Image_im::executeConvertCmd(): %s", $cmd));
+        exec($cmd, $output, $retval);
+        if ($retval) {
+            $this->_logErr(sprintf("Error running command: %s", $cmd . "\n" . implode("\n", $output)));
+        }
+        $this->_data = file_get_contents($tmpout);
+
+        @unlink($tmpin);
+        @unlink($tmpout);
+    }
+
+
+    /**
+     * Return point size for font
+     */
+    public static function getFontSize($fontsize)
+    {
+        switch ($fontsize) {
+        case 'medium':
+            $point = 18;
+            break;
+        case 'large':
+            $point = 24;
+            break;
+        case 'giant':
+            $point = 30;
+            break;
+        default:
+            $point = 12;
+        }
+
+        return $point;
+    }
+
+
+    /**
+     * Get the version of the convert command available. This needs to be
+     * publicly visable since it's used by various Effects.
+     *
+     * @return A version string suitable for using in version_compare()
+     */
+    public function getIMVersion()
+    {
+        static $version = null;
+        if (!is_array($version)) {
+            if (!is_null($this->_imagick)) {
+                $output = $this->_imagick->getVersion();
+                $output[0] = $output['versionString'];
+            } else {
+                $commandline = $this->_convert . ' --version';
+                exec($commandline, $output, $retval);
+            }
+            if (preg_match('/([0-9])\.([0-9])\.([0-9])/', $output[0], $matches)) {
+                $version = $matches;
+                return $matches;
+            } else {
+               return false;
+            }
+        }
+        return $version;
+    }
+
+    public function addPostSrcOperation($operation)
+    {
+        $this->_postSrcOperations[] = $operation;
+    }
+
+    public function addOperation($operation)
+    {
+        $this->_operations[] = $operation;
+    }
+
+    public function addFileToClean($filename)
+    {
+        $this->_toClean[] = $filename;
+    }
+
+    public function getConvertPath()
+    {
+        return $this->_convert;
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Imagick.php b/framework/Image/lib/Horde/Image/Imagick.php
new file mode 100644 (file)
index 0000000..94fd3e8
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+/**
+ * Imagick driver for the Horde_Image API
+ *
+ * Copyright 2007-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Michael J. Rubinsky <mrubinsk@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Imagick extends Horde_Image
+{
+    protected $_imagick;
+
+    public function __construct($params, $context = array())
+    {
+        parent::__construct($params, $context);
+        if (Util::loadExtension('imagick')) {
+            ini_set('imagick.locale_fix', 1);
+            $this->_imagick = new Imagick();
+            $this->_width = max(array($this->_width, 1));
+            $this->_height = max(array($this->_height, 1));
+            if (!empty($params['filename'])) {
+                $this->loadFile($params['filename']);
+            } elseif(!empty($params['data'])) {
+                $this->loadString(md5($params['data']), $params['data']);
+            } else {
+                $this->_imagick->newImage($this->_width, $this->_height, $this->_background);
+                $this->_data = $this->_imagick->getImageBlob();
+            }
+            $this->_imagick->setImageFormat($this->_type);
+        }
+    }
+
+    /**
+     * Load image data from a string.
+     *
+     * @TODO: iterator???
+     *
+     * @param string $id
+     * @param string $image_data
+     *
+     * @return void
+     */
+    public function loadString($id, $image_data)
+    {
+        parent::loadString($id, $image_data);
+        $this->_imagick->clear();
+        $this->_imagick->readImageBlob($image_data);
+        $this->_imagick->setFormat($this->_type);
+        $this->_imagick->setIteratorIndex(0);
+    }
+
+    /**
+     * Load the image data from a file.
+     *
+     * @param string $filename  The full path and filename to the file to load
+     *                          the image data from. The filename will also be
+     *                          used for the image id.
+     *
+     * @return mixed
+     */
+    public function loadFile($filename)
+    {
+        // parent function loads image data into $this->_data
+        // @TODO: Can we clear the _data variable to save memory?
+        parent::loadFile($filename);
+        $this->loadFile($this->_data);
+    }
+
+    /*
+     * Return the raw image data.
+     *
+     * @param boolean $convert  Ignored for imagick driver.
+     *
+     * @return string  The raw image data.
+     */
+    public function raw($convert = false)
+    {
+        return $this->_imagick->getImageBlob();
+    }
+
+    public function reset()
+    {
+        parent::reset();
+        $this->_imagick->clear();
+    }
+
+    /**
+     * Resize current image.
+     *
+     * @see Horde_Image_im::resize()
+     *
+     * @return void
+     */
+    public function resize($width, $height, $ratio = true, $keepProfile = false)
+    {
+        if ($keepProfile) {
+            $this->_imagick->resizeImage($width, $height, $ratio);
+        } else {
+            $this->_imagick->thumbnailImage($width, $height, $ratio);
+        }
+        $this->_width = 0;
+        $this->_height = 0;
+    }
+
+    /**
+     * *ALWAYS* use getDimensions() to get image geometry...instance
+     * variables only cache geometry until it changes, then they go
+     * to zero.
+     *
+     */
+    public function getDimensions()
+    {
+        if ($this->_height == 0 && $this->_width == 0) {
+            try {
+                $size = $this->_imagick->getImageGeometry();
+            catch (ImagickException $e) {
+                //@TODO - Rethrow as Horde_Image_Exception
+            }
+
+            $this->_height = $size['height'];
+            $this->_width = $size['width'];
+        }
+
+        return array('width' => $this->_width,
+                     'height' => $this->_height);
+
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Png.php b/framework/Image/lib/Horde/Image/Png.php
new file mode 100644 (file)
index 0000000..6b45364
--- /dev/null
@@ -0,0 +1,243 @@
+<?php
+/**
+ * This class implements the Horde_Image:: API for PNG images. It
+ * mainly provides some utility functions, such as the ability to make
+ * pixels or solid images for now.
+ *
+ * $Horde: framework/Image/Image/png.php,v 1.30 2009/01/06 17:49:20 jan Exp $
+ *
+ * Copyright 2003-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Mike Cochrane <mike@graftonhall.co.nz>
+ * @since   Horde 3.0
+ * @package Horde_Image
+ */
+class Horde_Image_Png extends Horde_Image {
+
+    /**
+     * The array of pixel data.
+     *
+     * @var array
+     */
+    var $_img = array();
+
+    /**
+     * Color depth (only 8 and 16 implemented).
+     *
+     * @var integer
+     */
+    var $_colorDepth = 8;
+
+    /**
+     * Color type (only 2 (true color) implemented).
+     *
+     * @var integer
+     */
+    var $_colorType = 2;
+
+    /**
+     * Compression method (0 is the only current valid value).
+     *
+     * @var integer
+     */
+    var $_compressionMethod = 0;
+
+    /**
+     * Filter method (0 is the only current valid value).
+     *
+     * @var integer
+     */
+    var $_filterMethod = 0;
+
+    /**
+     * Interlace method (only 0 (no interlace) implemented).
+     *
+     * @var integer
+     */
+    var $_interlaceMethod = 0;
+
+    /**
+     * PNG image constructor.
+     */
+    function Horde_Image_png($params)
+    {
+        parent::Horde_Image($params);
+
+        if (!empty($params['width'])) {
+            $this->rectangle(0, 0, $params['width'], $params['height'], $this->_background, $this->_background);
+        }
+    }
+
+    function getContentType()
+    {
+        return 'image/png';
+    }
+
+    /**
+     * Return the raw data for this image.
+     *
+     * @return string  The raw image data.
+     */
+    function raw()
+    {
+        return
+            $this->_header() .
+            $this->_IHDR() .
+
+            /* Say what created the image file. */
+            $this->_tEXt('Software', 'Horde Framework Image_png Class') .
+
+            /* Set the last modified date/time. */
+            $this->_tIME() .
+
+            $this->_IDAT() .
+            $this->_IEND();
+    }
+
+    /**
+     * Reset the image data.
+     */
+    function reset()
+    {
+        parent::reset();
+        $this->_img = array();
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rectangle with.
+     */
+    function rectangle($x, $y, $width, $height, $color = 'black', $fill = 'none')
+    {
+        list($r, $g, $b) = $this->getRGB($color);
+        if ($fill != 'none') {
+            list($fR, $fG, $fB) = $this->getRGB($fill);
+        }
+
+        $x2 = $x + $width;
+        $y2 = $y + $height;
+
+        for ($h = $y; $h <= $y2; $h++) {
+            for ($w = $x; $w <= $x2; $w++) {
+                // See if we're on an edge.
+                if ($w == $x || $h == $y || $w == $x2 || $h == $y2) {
+                    $this->_img[$h][$w] = array('r' => $r, 'g' => $g, 'b' => $b);
+                } elseif ($fill != 'none') {
+                    $this->_img[$h][$w] = array('r' => $fR, 'g' => $fG, 'b' => $fB);
+                }
+            }
+        }
+    }
+
+    /**
+     * Create the PNG file header.
+     */
+    function _header()
+    {
+        return pack('CCCCCCCC', 137, 80, 78, 71, 13, 10, 26, 10);
+    }
+
+    /**
+     * Create Image Header block.
+     */
+    function _IHDR()
+    {
+        $data = pack('a4NNCCCCC', 'IHDR', $this->_width, $this->_height, $this->_colorDepth, $this->_colorType, $this->_compressionMethod, $this->_filterMethod, $this->_interlaceMethod);
+        return pack('Na' . strlen($data) . 'N', strlen($data) - 4, $data, crc32($data));
+    }
+
+    /**
+     * Create IEND block.
+     */
+    function _IEND()
+    {
+        $data = 'IEND';
+        return pack('Na' . strlen($data) . 'N', strlen($data) - 4, $data, crc32($data));
+    }
+
+    /**
+     * Create Image Data block.
+     */
+    function _IDAT()
+    {
+        $data = '';
+        $prevscanline = null;
+        $filter = 0;
+        for ($i = 0; $i < $this->_height; $i++) {
+            $scanline = array();
+            $data .= chr($filter);
+            for ($j = 0; $j < $this->_width; $j++) {
+                if ($this->_colorDepth == 8) {
+                    $scanline[$j] = pack('CCC', $this->_img[$i][$j]['r'], $this->_img[$i][$j]['g'], $this->_img[$i][$j]['b']);
+                } elseif ($this->_colorDepth == 16) {
+                    $scanline[$j] = pack('nnn', $this->_img[$i][$j]['r'] << 8, $this->_img[$i][$j]['g'] << 8, $this->_img[$i][$j]['b'] << 8);
+                }
+
+                if ($filter == 0) {
+                    /* No Filter. */
+                    $data .= $scanline[$j];
+                } elseif ($filter == 2) {
+                    /* Up Filter. */
+                    $pixel = $scanline[$j] - $prevscanline[$j];
+                    if ($this->_colorDepth == 8) {
+                        $data .= pack('CCC', $pixel >> 16, ($pixel >> 8) & 0xFF, $pixel & 0xFF);
+                    } elseif ($this->_colorDepth == 16) {
+                        $data .= pack('nnn', ($pixel >> 32), ($pixel >> 16) & 0xFFFF, $pixel & 0xFFFF);
+                    }
+                }
+            }
+            $prevscanline = $scanline;
+        }
+        $compressed = gzdeflate($data, 9);
+
+        $data = 'IDAT' . pack('CCa' . strlen($compressed) . 'a4', 0x78, 0x01, $compressed, $this->_Adler32($data));
+        return pack('Na' . strlen($data) . 'N', strlen($data) - 4, $data, crc32($data));
+    }
+
+    /**
+     * Create tEXt block.
+     */
+    function _tEXt($keyword, $text)
+    {
+        $data = 'tEXt' . $keyword . "\0" . $text;
+        return pack('Na' . strlen($data) . 'N', strlen($data) - 4, $data, crc32($data));
+    }
+
+    /**
+     * Create last modified time block.
+     */
+    function _tIME($date = null)
+    {
+        if (is_null($date)) {
+            $date = time();
+        }
+
+        $data = 'tIME' . pack('nCCCCC', intval(date('Y', $date)), intval(date('m', $date)), intval(date('j', $date)), intval(date('G', $date)), intval(date('i', $date)), intval(date('s', $date)));
+        return pack('Na' . strlen($data) . 'N', strlen($data) - 4, $data, crc32($data));
+    }
+
+    /**
+     * Calculate an Adler32 checksum for a string.
+     */
+    function _Adler32($input)
+    {
+        $s1 = 1;
+        $s2 = 0;
+        $iMax = strlen($input);
+        for ($i = 0; $i < $iMax; $i++) {
+            $s1 = ($s1 + ord($input[$i])) % 0xFFF1;
+            $s2 = ($s2 + $s1) % 0xFFF1;
+        }
+        return pack('N', (($s2 << 16) | $s1));
+    }
+
+}
diff --git a/framework/Image/lib/Horde/Image/Svg.php b/framework/Image/lib/Horde/Image/Svg.php
new file mode 100644 (file)
index 0000000..36517b7
--- /dev/null
@@ -0,0 +1,338 @@
+<?php
+/**
+ * This class implements the Horde_Image:: API for SVG.
+ *
+ * Copyright 2002-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @package Horde_Image
+ */
+class Horde_Image_Svg extends Horde_Image
+{
+    protected $_svg;
+
+    /**
+     * Capabilites of this driver.
+     *
+     * @var array
+     */
+    protected $_capabilities = array('canvas');
+
+    public function __construct($params)
+    {
+        parent::__construct($params);
+        $this->_svg = new XML_SVG_Document(array('width' => $this->_width,
+                                                 'height' => $this->_height));
+    }
+
+    public function getContentType()
+    {
+        return 'image/svg+xml';
+    }
+
+    public function display()
+    {
+        $this->_svg->printElement();
+    }
+
+    /**
+     * Return the raw data for this image.
+     *
+     * @return string  The raw image data.
+     */
+    public function raw()
+    {
+        return $this->_svg->bufferObject();
+    }
+
+    private function _createSymbol($s, $id)
+    {
+        $s->setParam('id', $id);
+        $defs = new XML_SVG_Defs();
+        $defs->addChild($s);
+        $this->_svg->addChild($defs);
+    }
+
+    private function _createDropShadow($id = 'dropShadow')
+    {
+        $defs = new XML_SVG_Defs();
+        $filter = new XML_SVG_Filter(array('id' => $id));
+        $filter->addPrimitive('GaussianBlur', array('in' => 'SourceAlpha',
+                                                    'stdDeviation' => 2,
+                                                    'result' => 'blur'));
+        $filter->addPrimitive('Offset', array('in' => 'blur',
+                                              'dx' => 4,
+                                              'dy' => 4,
+                                              'result' => 'offsetBlur'));
+        $merge = new XML_SVG_FilterPrimitive('Merge');
+        $merge->addMergeNode('offsetBlur');
+        $merge->addMergeNode('SourceGraphic');
+
+        $filter->addChild($merge);
+        $defs->addChild($filter);
+        $this->_svg->addChild($defs);
+    }
+
+    /**
+     * Draws a text string on the image in a specified location, with
+     * the specified style information.
+     *
+     * @param string  $text       The text to draw.
+     * @param integer $x          The left x coordinate of the start of the text string.
+     * @param integer $y          The top y coordinate of the start of the text string.
+     * @param string  $font       The font identifier you want to use for the text.
+     * @param string  $color      The color that you want the text displayed in.
+     * @param integer $direction  An integer that specifies the orientation of the text.
+     */
+    public function text($string, $x, $y, $font = 'monospace', $color = 'black', $direction = 0)
+    {
+        $height = 12;
+        $style = 'font-family:' . $font . ';font-height:' . $height . 'px;fill:' . $this->getHexColor($color) . ';text-anchor:start;';
+        $transform = 'rotate(' . $direction . ',' . $x . ',' . $y . ')';
+        $this->_svg->addChild(new XML_SVG_Text(array('text' => $string,
+                                                     'x' => (int)$x,
+                                                     'y' => (int)$y + $height,
+                                                     'transform' => $transform,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw a circle.
+     *
+     * @param integer $x      The x coordinate of the centre.
+     * @param integer $y      The y coordinate of the centre.
+     * @param integer $r      The radius of the circle.
+     * @param string  $color  The line color of the circle.
+     * @param string  $fill   The color to fill the circle.
+     */
+    public function circle($x, $y, $r, $color, $fill = null)
+    {
+        if (!empty($fill)) {
+            $style = 'fill:' . $this->getHexColor($fill) . '; ';
+        } else {
+            $style = 'fill:none;';
+        }
+        $style .= 'stroke:' . $this->getHexColor($color) . '; stroke-width:1';
+
+        $this->_svg->addChild(new XML_SVG_Circle(array('cx' => $x,
+                                                       'cy' => $y,
+                                                       'r' => $r,
+                                                       'style' => $style)));
+    }
+
+    /**
+     * Draw a polygon based on a set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the polygon with.
+     * @param string $fill     The color to fill the polygon.
+     */
+    public function polygon($verts, $color, $fill = null)
+    {
+        if (!empty($fill)) {
+            $style = 'fill:' . $this->getHexColor($fill) . '; ';
+        } else {
+            $style = 'fill:none;';
+        }
+        $style .= 'stroke:' . $this->getHexColor($color) . '; stroke-width:1';
+
+        $points = '';
+        foreach ($verts as $v) {
+            $points .= $v['x'] . ',' . $v['y'] . ' ';
+        }
+        $points = trim($points);
+
+        $this->_svg->addChild(new XML_SVG_Polygon(array('points' => $points,
+                                                        'style' => $style)));
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rectangle.
+     */
+    public function rectangle($x, $y, $width, $height, $color, $fill = null)
+    {
+        if (!empty($fill)) {
+            $style = 'fill:' . $this->getHexColor($fill) . '; ';
+        } else {
+            $style = 'fill:none;';
+        }
+        $style .= 'stroke:' . $this->getHexColor($color) . '; stroke-width:1';
+
+        $this->_svg->addChild(new XML_SVG_Rect(array('x' => $x,
+                                                     'y' => $y,
+                                                     'width' => $width,
+                                                     'height' => $height,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param integer $round   The width of the corner rounding.
+     * @param string  $color   The line color of the rectangle.
+     * @param string  $fill    The color to fill the rectangle.
+     */
+    public function roundedRectangle($x, $y, $width, $height, $round, $color, $fill)
+    {
+        if (!empty($fill)) {
+            $style = 'fill:' . $this->getHexColor($fill) . '; ';
+        } else {
+            $style = 'fill:none;';
+        }
+        $style .= 'stroke:' . $this->getHexColor($color) . '; stroke-width:1';
+
+        $this->_svg->addChild(new XML_SVG_Rect(array('x' => $x,
+                                                     'y' => $y,
+                                                     'rx' => $round,
+                                                     'ry' => $round,
+                                                     'width' => $width,
+                                                     'height' => $height,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw a line.
+     *
+     * @param integer $x0     The x coordinate of the start.
+     * @param integer $y0     The y coordinate of the start.
+     * @param integer $x1     The x coordinate of the end.
+     * @param integer $y1     The y coordinate of the end.
+     * @param string $color   The line color.
+     * @param string $width   The width of the line.
+     */
+    public function line($x1, $y1, $x2, $y2, $color = 'black', $width = 1)
+    {
+        $style = 'stroke:' . $this->getHexColor($color) . '; stroke-width:' . (int)$width;
+        $this->_svg->addChild(new XML_SVG_Line(array('x1' => $x1,
+                                                     'y1' => $y1,
+                                                     'x2' => $x2,
+                                                     'y2' => $y2,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw a dashed line.
+     *
+     * @param integer $x0           The x coordinate of the start.
+     * @param integer $y0           The y coordinate of the start.
+     * @param integer $x1           The x coordinate of the end.
+     * @param integer $y1           The y coordinate of the end.
+     * @param string  $color        The line color.
+     * @param string  $width        The width of the line.
+     * @param integer $dash_length  The length of a dash on the dashed line
+     * @param integer $dash_space   The length of a space in the dashed line
+     */
+    public function dashedLine($x1, $y1, $x2, $y2, $color = 'black', $width = 1, $dash_length = 2, $dash_space = 2)
+    {
+        $style = 'stroke:' . $this->getHexColor($color) . '; stroke-width:' . (int)$width . '; stroke-dasharray:' . $dash_length . ',' . $dash_space . ';';
+        $this->_svg->addChild(new XML_SVG_Line(array('x1' => $x1,
+                                                     'y1' => $y1,
+                                                     'x2' => $x2,
+                                                     'y2' => $y2,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw a polyline (a non-closed, non-filled polygon) based on a
+     * set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the line with.
+     * @param string $width    The width of the line.
+     */
+    public function polyline($verts, $color, $width = 1)
+    {
+        $style = 'stroke:' . $this->getHexColor($color) . '; stroke-width:' . $width . ';fill:none;';
+
+        // Calculate the path entry.
+        $path = '';
+
+        $first = true;
+        foreach ($verts as $vert) {
+            if ($first) {
+                $first = false;
+                $path .= 'M ' . $vert['x'] . ',' . $vert['y'];
+            } else {
+                $path .= ' L ' . $vert['x'] . ',' . $vert['y'];
+            }
+        }
+
+        $this->_svg->addChild(new XML_SVG_Path(array('d' => $path,
+                                                     'style' => $style)));
+    }
+
+    /**
+     * Draw an arc.
+     *
+     * @param integer $x      The x coordinate of the centre.
+     * @param integer $y      The y coordinate of the centre.
+     * @param integer $r      The radius of the arc.
+     * @param integer $start  The start angle of the arc.
+     * @param integer $end    The end angle of the arc.
+     * @param string  $color  The line color of the arc.
+     * @param string  $fill   The fill color of the arc (defaults to none).
+     */
+    public function arc($x, $y, $r, $start, $end, $color = 'black', $fill = null)
+    {
+        if (!empty($fill)) {
+            $style = 'fill:' . $this->getHexColor($fill) . '; ';
+        } else {
+            $style = 'fill:none;';
+        }
+        $style .= 'stroke:' . $this->getHexColor($color) . '; stroke-width:1';
+
+        $mid = round(($start + $end) / 2);
+
+        // Calculate the path entry.
+        $path = '';
+
+        // If filled, draw the outline.
+        if (!empty($fill)) {
+            // Start at the center of the ellipse the arc is on.
+            $path .= "M $x,$y ";
+
+            // Draw out to ellipse edge.
+            list($arcX, $arcY) = $this->_circlePoint($start, $r * 2);
+            $path .= 'L ' . round($x + $arcX) . ',' .
+                round($y + $arcY) . ' ';
+        }
+
+        // Draw arcs.
+        list($arcX, $arcY) = $this->_circlePoint($mid, $r * 2);
+        $path .= "A $r,$r 0 0 1 " .
+            round($x + $arcX) . ',' .
+            round($y + $arcY) . ' ';
+
+        list($arcX, $arcY) = $this->_circlePoint($end, $r * 2);
+        $path .= "A $r,$r 0 0 1 " .
+            round($x + $arcX) . ',' .
+            round($y + $arcY) . ' ';
+
+        // If filled, close the outline.
+        if (!empty($fill)) {
+            $path .= 'Z';
+        }
+
+        $path = trim($path);
+
+        $this->_svg->addChild(new XML_SVG_Path(array('d' => $path,
+                                                     'style' => $style)));
+    }
+
+}
\ No newline at end of file
diff --git a/framework/Image/lib/Horde/Image/Swf.php b/framework/Image/lib/Horde/Image/Swf.php
new file mode 100644 (file)
index 0000000..d328efe
--- /dev/null
@@ -0,0 +1,532 @@
+<?php
+
+require_once dirname(__FILE__) . '/../Image.php';
+
+/**
+ * This class implements the Horde_Image:: API for SWF, using the PHP
+ * Ming extension.
+ *
+ * $Horde: framework/Image/Image/swf.php,v 1.35 2009/01/06 17:49:20 jan Exp $
+ *
+ * Copyright 2002-2009 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @since   Horde 3.0
+ * @package Horde_Image
+ */
+class Horde_Image_Swf extends Horde_Image {
+
+    /**
+     * Capabilites of this driver.
+     *
+     * @var array
+     */
+    var $_capabilities = array('canvas');
+
+    /**
+     * SWF root movie.
+     *
+     * @var resource
+     */
+    var $_movie;
+
+    function Horde_Image_swf($params)
+    {
+        parent::Horde_Image($params);
+
+        $this->_movie = new SWFMovie();
+        $this->_movie->setDimension($this->_width, $this->_height);
+
+        // FIXME: honor the 'background' parameter here.
+        $this->_movie->setBackground(0xff, 0xff, 0xff);
+        $this->_movie->setRate(30);
+    }
+
+    function getContentType()
+    {
+        return 'application/x-shockwave-flash';
+    }
+
+    /**
+     * Display the movie.
+     */
+    function display()
+    {
+        $this->headers();
+        $this->_movie->output();
+    }
+
+    /**
+     * Return the raw data for this image.
+     *
+     * @return string  The raw image data.
+     */
+    function raw()
+    {
+        ob_start();
+        $this->_movie->output();
+        $data = ob_get_contents();
+        ob_end_clean();
+
+        return $data;
+    }
+
+    /**
+     * Creates a color that can be accessed in this object. When a
+     * color is set, the rgba values are returned in an array.
+     *
+     * @param string $name  The name of the color.
+     *
+     * @return array  The red, green, blue, alpha values of the color.
+     */
+    function allocateColor($name)
+    {
+        list($r, $g, $b) = $this->getRGB($name);
+        return array('red' => $r,
+                     'green' => $g,
+                     'blue' => $b,
+                     'alpha' => 255);
+    }
+
+    function getFont($font)
+    {
+        switch ($font) {
+        case 'sans-serif':
+            return '_sans';
+
+        case 'serif':
+            return '_serif';
+
+        case 'monospace':
+            return '_typewriter';
+
+        default:
+            return $font;
+        }
+    }
+
+    /**
+     * Draws a text string on the image in a specified location, with
+     * the specified style information.
+     *
+     * @param string  $text       The text to draw.
+     * @param integer $x          The left x coordinate of the start of the text string.
+     * @param integer $y          The top y coordinate of the start of the text string.
+     * @param string  $font       The font identifier you want to use for the text.
+     * @param string  $color      The color that you want the text displayed in.
+     * @param integer $direction  An integer that specifies the orientation of the text.
+     */
+    function text($string, $x, $y, $font = 'monospace', $color = 'black', $direction = 0)
+    {
+        $color = $this->allocateColor($color);
+
+        if (!strncasecmp(PHP_OS, 'WIN', 3)) {
+            $text = new SWFTextField(SWFTEXTFIELD_NOEDIT);
+        } else {
+            $text = new SWFText();
+        }
+        $text->setColor($color['red'], $color['green'], $color['blue'], $color['alpha']);
+        $text->addString($string);
+        $text->setFont(new SWFFont($this->getFont($font)));
+
+        $t = $this->_movie->add($text);
+        $t->moveTo($x, $y);
+        $t->rotate($direction);
+
+        return $t;
+    }
+
+    /**
+     * Draw a circle.
+     *
+     * @param integer $x      The x co-ordinate of the centre.
+     * @param integer $y      The y co-ordinate of the centre.
+     * @param integer $r      The radius of the circle.
+     * @param string  $color  The line color of the circle.
+     * @param string  $fill   The color to fill the circle.
+     */
+    function circle($x, $y, $r, $color, $fill = 'none')
+    {
+        $s = new SWFShape();
+        $color = $this->allocateColor($color);
+        $s->setLine(1, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+
+        if ($fill != 'none') {
+            $fillColor = $this->allocateColor($fill);
+            $f = $s->addFill($fillColor['red'], $fillColor['green'], $fillColor['blue'], $fillColor['alpha']);
+            $s->setRightFill($f);
+        }
+
+        $a = $r * 0.414213562; // = tan(22.5 deg)
+        $b = $r * 0.707106781; // = sqrt(2)/2 = sin(45 deg)
+
+        $s->movePenTo($x + $r, $y);
+
+        $s->drawCurveTo($x + $r, $y - $a, $x + $b, $y - $b);
+        $s->drawCurveTo($x + $a, $y - $r, $x, $y - $r);
+        $s->drawCurveTo($x - $a, $y - $r, $x - $b, $y - $b);
+        $s->drawCurveTo($x - $r, $y - $a, $x - $r, $y);
+        $s->drawCurveTo($x - $r, $y + $a, $x - $b, $y + $b);
+        $s->drawCurveTo($x - $a, $y + $r, $x, $y + $r);
+        $s->drawCurveTo($x + $a, $y + $r, $x + $b, $y + $b);
+        $s->drawCurveTo($x + $r, $y + $a, $x + $r, $y);
+
+        return $this->_movie->add($s);
+    }
+
+    /**
+     * Draw a polygon based on a set of vertices.
+     *
+     * @param array $vertices  An array of x and y labeled arrays
+     *                         (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string $color    The color you want to draw the polygon with.
+     * @param string $fill     The color to fill the polygon.
+     */
+    function polygon($verts, $color, $fill = 'none')
+    {
+        $color = $this->allocateColor($color);
+
+        if (is_array($color) && is_array($verts) && (sizeof($verts) > 2)) {
+            $shape = new SWFShape();
+            $shape->setLine(1, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+
+            if ($fill != 'none') {
+                $fillColor = $this->allocateColor($fill);
+                $f = $shape->addFill($fillColor['red'], $fillColor['green'], $fillColor['blue'], $fillColor['alpha']);
+                $shape->setRightFill($f);
+            }
+
+            $first_done = false;
+            foreach ($verts as $value) {
+                if (!$first_done) {
+                    $shape->movePenTo($value['x'], $value['y']);
+                    $first_done = true;
+                    $first_x = $value['x'];
+                    $first_y = $value['y'];
+                }
+                $shape->drawLineTo($value['x'], $value['y']);
+            }
+            $shape->drawLineTo($first_x, $first_y);
+
+            return $this->_movie->add($shape);
+        } else {
+            // If the color is an array and the vertices is a an array
+            // of more than 2 points.
+            return false;
+        }
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string  $color   The line color of the rectangle.
+     * @param string  $fill    The color to fill the rectangle.
+     */
+    function rectangle($x, $y, $width, $height, $color, $fill = 'none')
+    {
+        $verts[0] = array('x' => $x, 'y' => $y);
+        $verts[1] = array('x' => $x + $width, 'y' => $y);
+        $verts[2] = array('x' => $x + $width, 'y' => $y + $height);
+        $verts[3] = array('x' => $x, 'y' => $y + $height);
+
+        return $this->polygon($verts, $color, $fill);
+    }
+
+    /**
+     * Draw a rectangle.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param integer $round   The width of the corner rounding.
+     * @param string $color    The line color of the rectangle.
+     * @param string $fill     The color to fill the rectangle.
+     */
+    function roundedRectangle($x, $y, $width, $height, $round, $color = 'black', $fill = 'none')
+    {
+        if ($round <= 0) {
+            // Optimize out any calls with no corner rounding.
+            return $this->rectangle($x, $y, $width, $height, $color, $fill);
+        }
+
+        $s = new SWFShape();
+        $color = $this->allocateColor($color);
+        $s->setLine(1, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+
+        if ($fill != 'none') {
+            $fillColor = $this->allocateColor($fill);
+            $f = $s->addFill($fillColor['red'], $fillColor['green'], $fillColor['blue'], $fillColor['alpha']);
+            $s->setRightFill($f);
+        }
+
+        // Set corner points to avoid lots of redundant math.
+        $x1 = $x + $round;
+        $y1 = $y + $round;
+
+        $x2 = $x + $width - $round;
+        $y2 = $y + $round;
+
+        $x3 = $x + $width - $round;
+        $y3 = $y + $height - $round;
+
+        $x4 = $x + $round;
+        $y4 = $y + $height - $round;
+
+        // Start in the upper left.
+        $p1 = $this->_arcPoints($round, 180, 225);
+        $p2 = $this->_arcPoints($round, 225, 270);
+
+        // Start at the lower left corner of the top left curve.
+        $s->movePenTo($x1 + $p1['x1'], $y1 + $p1['y1']);
+
+        // Draw the upper left corner.
+        $s->drawCurveTo($x1 + $p1['x3'], $y1 + $p1['y3'], $x1 + $p1['x2'], $y1 + $p1['y2']);
+        $s->drawCurveTo($x1 + $p2['x3'], $y1 + $p2['y3'], $x1 + $p2['x2'], $y1 + $p2['y2']);
+
+        // Calculate the upper right points.
+        $p3 = $this->_arcPoints($round, 270, 315);
+        $p4 = $this->_arcPoints($round, 315, 360);
+
+        // Connect the top left and right curves.
+        $s->drawLineTo($x2 + $p3['x1'], $y2 + $p3['y1']);
+
+        // Draw the upper right corner.
+        $s->drawCurveTo($x2 + $p3['x3'], $y2 + $p3['y3'], $x2 + $p3['x2'], $y2 + $p3['y2']);
+        $s->drawCurveTo($x2 + $p4['x3'], $y2 + $p4['y3'], $x2 + $p4['x2'], $y2 + $p4['y2']);
+
+        // Calculate the lower right points.
+        $p5 = $this->_arcPoints($round, 0, 45);
+        $p6 = $this->_arcPoints($round, 45, 90);
+
+        // Connect the top right and lower right curves.
+        $s->drawLineTo($x3 + $p5['x1'], $y3 + $p5['y1']);
+
+        // Draw the lower right corner.
+        $s->drawCurveTo($x3 + $p5['x3'], $y3 + $p5['y3'], $x3 + $p5['x2'], $y3 + $p5['y2']);
+        $s->drawCurveTo($x3 + $p6['x3'], $y3 + $p6['y3'], $x3 + $p6['x2'], $y3 + $p6['y2']);
+
+        // Calculate the lower left points.
+        $p7 = $this->_arcPoints($round, 90, 135);
+        $p8 = $this->_arcPoints($round, 135, 180);
+
+        // Connect the bottom right and bottom left curves.
+        $s->drawLineTo($x4 + $p7['x1'], $y4 + $p7['y1']);
+
+        // Draw the lower left corner.
+        $s->drawCurveTo($x4 + $p7['x3'], $y4 + $p7['y3'], $x4 + $p7['x2'], $y4 + $p7['y2']);
+        $s->drawCurveTo($x4 + $p8['x3'], $y4 + $p8['y3'], $x4 + $p8['x2'], $y4 + $p8['y2']);
+
+        // Close the shape.
+        $s->drawLineTo($x1 + $p1['x1'], $y1 + $p1['y1']);
+
+        return $this->_movie->add($s);
+    }
+
+    /**
+     * Draw a line.
+     *
+     * @param integer $x0     The x co-ordinate of the start.
+     * @param integer $y0     The y co-ordinate of the start.
+     * @param integer $x1     The x co-ordinate of the end.
+     * @param integer $y1     The y co-ordinate of the end.
+     * @param string  $color  The line color.
+     * @param string  $width  The width of the line.
+     */
+    function line($x1, $y1, $x2, $y2, $color = 'black', $width = 1)
+    {
+        $color = $this->allocateColor($color);
+
+        if (is_array($color)) {
+            $shape = new SWFShape();
+            $shape->setLine($width, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+            $shape->movePenTo($x1, $y1);
+            $shape->drawLineTo($x2, $y2);
+
+            return $this->_movie->add($shape);
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Draw a dashed line.
+     *
+     * @param integer $x0           The x co-ordinate of the start.
+     * @param integer $y0           The y co-ordinate of the start.
+     * @param integer $x1           The x co-ordinate of the end.
+     * @param integer $y1           The y co-ordinate of the end.
+     * @param string  $color        The line color.
+     * @param string  $width        The width of the line.
+     * @param integer $dash_length  The length of a dash on the dashed line
+     * @param integer $dash_space   The length of a space in the dashed line
+     */
+    function dashedLine($x0, $y0, $x1, $y1, $color = 'black', $width = 1, $dash_length = 2, $dash_space = 2)
+    {
+        // Get the length of the line in pixels.
+        $line_length = max(ceil(sqrt(pow(($x1 - $x0), 2) + pow(($y1 - $y0), 2))), 2);
+
+        $cosTheta = ($x1 - $x0) / $line_length;
+        $sinTheta = ($y1 - $y0) / $line_length;
+        $lastx = $x0;
+        $lasty = $y0;
+
+        // Draw the dashed line.
+        for ($i = 0; $i < $line_length; $i += ($dash_length + $dash_space)) {
+            $x = ($dash_length * $cosTheta) + $lastx;
+            $y = ($dash_length * $sinTheta) + $lasty;
+
+            $this->line($lastx, $lasty, $x, $y, $color);
+
+            $lastx = $x + ($dash_space * $cosTheta);
+            $lasty = $y + ($dash_space * $sinTheta);
+        }
+    }
+
+    /**
+     * Draw a polyline (a non-closed, non-filled polygon) based on a
+     * set of vertices.
+     *
+     * @param array   $vertices  An array of x and y labeled arrays
+     *                           (eg. $vertices[0]['x'], $vertices[0]['y'], ...).
+     * @param string  $color     The color you want to draw the line with.
+     * @param string  $width     The width of the line.
+     */
+    function polyline($verts, $color, $width = 1)
+    {
+        $color = $this->allocateColor($color);
+
+        $shape = new SWFShape();
+        $shape->setLine($width, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+
+        $first_done = false;
+        foreach ($verts as $value) {
+            if (!$first_done) {
+                $shape->movePenTo($value['x'], $value['y']);
+                $first_done = true;
+            }
+            $shape->drawLineTo($value['x'], $value['y']);
+        }
+
+        return $this->_movie->add($shape);
+    }
+
+    /**
+     * Draw an arc.
+     *
+     * @param integer $x      The x co-ordinate of the centre.
+     * @param integer $y      The y co-ordinate of the centre.
+     * @param integer $r      The radius of the arc.
+     * @param integer $start  The start angle of the arc.
+     * @param integer $end    The end angle of the arc.
+     * @param string $color   The line color of the arc.
+     * @param string $fill    The fill color of the arc.
+     */
+    function arc($x, $y, $r, $start, $end, $color = 'black', $fill = 'none')
+    {
+        $s = new SWFShape();
+        $color = $this->allocateColor($color);
+        $s->setLine(1, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+
+        if ($fill != 'none') {
+            $fillColor = $this->allocateColor($fill);
+            $f = $s->addFill($fillColor['red'], $fillColor['green'], $fillColor['blue'], $fillColor['alpha']);
+            $s->setRightFill($f);
+        }
+
+        if ($end - $start <= 45) {
+            $pts = $this->_arcPoints($r, $start, $end);
+            $s->movePenTo($x, $y);
+            $s->drawLineTo($pts['x1'] + $x, $pts['y1'] + $y);
+            $s->drawCurveTo($pts['x3'] + $x, $pts['y3'] + $y, $pts['x2'] + $x, $pts['y2'] + $y);
+            $s->drawLineTo($x, $y);
+        } else {
+            $sections = ceil(($end - $start) / 45);
+            for ($i = 0; $i < $sections; $i++) {
+                $pts = $this->_arcPoints($r, $start + ($i * 45), ($start + (($i + 1) * 45) > $end)
+                                         ? $end
+                                         : ($start + (($i + 1) * 45)));
+
+                // If we are on the first section, move the pen to the
+                // centre and draw out to the edge.
+                if ($i == 0 && $fill != 'none') {
+                    $s->movePenTo($x, $y);
+                    $s->drawLineTo($pts['x1'] + $x, $pts['y1'] + $y);
+                } else {
+                    $s->movePenTo($pts['x1'] + $x, $pts['y1'] + $y);
+                }
+
+                // Draw the arc.
+                $s->drawCurveTo($pts['x3'] + $x, $pts['y3'] + $y, $pts['x2'] + $x, $pts['y2'] + $y);
+            }
+
+            if ($fill != 'none') {
+                // Draw a line from the edge back to the centre to close
+                // off the segment.
+                $s->drawLineTo($x, $y);
+            }
+        }
+
+        return $this->_movie->add($s);
+    }
+
+    /**
+     * Draw a rectangle filled with a gradient from $color1 to
+     * $color2.
+     *
+     * @param integer $x       The left x-coordinate of the rectangle.
+     * @param integer $y       The top y-coordinate of the rectangle.
+     * @param integer $width   The width of the rectangle.
+     * @param integer $height  The height of the rectangle.
+     * @param string  $color   The outline color of the rectangle.
+     * @param string  $fill1   The name of the start color for the gradient.
+     * @param string  $fill2   The name of the end color for the gradient.
+     */
+    function gradientRectangle($x, $y, $width, $height, $color = 'black', $fill1 = 'black', $fill2 = 'white')
+    {
+        $s = new SWFShape();
+
+        if ($color != 'none') {
+            $color = $this->allocateColor($color);
+            $s->setLine(1, $color['red'], $color['green'], $color['blue'], $color['alpha']);
+        }
+
+        $fill1 = $this->allocateColor($fill1);
+        $fill2 = $this->allocateColor($fill2);
+        $gradient = new SWFGradient();
+        $gradient->addEntry(0.0, $fill1['red'], $fill1['green'], $fill1['blue'], $fill1['alpha']);
+        $gradient->addEntry(1.0, $fill2['red'], $fill2['green'], $fill2['blue'], $fill2['alpha']);
+
+        $f = $s->addFill($gradient, SWFFILL_LINEAR_GRADIENT);
+        $f->scaleTo($width / $this->_width);
+        $f->moveTo($x, $y);
+        $s->setRightFill($f);
+
+        $verts[0] = array('x' => $x, 'y' => $y);
+        $verts[1] = array('x' => $x + $width, 'y' => $y);
+        $verts[2] = array('x' => $x + $width, 'y' => $y + $height);
+        $verts[3] = array('x' => $x, 'y' => $y + $height);
+
+        $first_done = false;
+        foreach ($verts as $vert) {
+            if (!$first_done) {
+                $s->movePenTo($vert['x'], $vert['y']);
+                $first_done = true;
+                $first_x = $vert['x'];
+                $first_y = $vert['y'];
+            }
+            $s->drawLineTo($vert['x'], $vert['y']);
+        }
+        $s->drawLineTo($first_x, $first_y);
+
+        return $this->_movie->add($s);
+    }
+
+}