function programmatically_create_post()
{
    $url = 'http://widgets.pinterest.com/v3/pidgets/boards/bradleyblose/my-stuff/pins/';
    $json_O = json_decode(file_get_contents($url), true);
    $id = $json_O['data']['pins'][0]['id'];
    $titlelink = 'https://www.pinterest.com/pin/' . $id . '/';
    $title = get_title($titlelink);
    var_dump($title);
    $original = $json_O['data']['pins'][0]['images']['237x']['url'];
    $image_url = preg_replace('/237x/', '736x', $original);
    $description = $json_O['data']['pins'][0]['description'];
    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;
    // Setup the author, slug, and title for the post
    $author_id = 1;
    $mytitle = get_page_by_title($title, OBJECT, 'post');
    var_dump($mytitle);
    // If the page doesn't already exist, then create it
    if (NULL == get_page_by_title($title, OBJECT, 'post')) {
        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $title, 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_type' => 'post'));
        //upload featured image
        $upload_dir = wp_upload_dir();
        $image_data = file_get_contents($image_url);
        $filename = basename($image_url);
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
            $path = $upload_dir['path'] . '/';
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
            $path = $upload_dir['basedir'] . '/';
        }
        file_put_contents($file, $image_data);
        //edit featured image to correct specs to fit theme
        $pngfilename = $filename . '.png';
        $targetThumb = $path . '/' . $pngfilename;
        $img = new Imagick($file);
        $img->scaleImage(250, 250, true);
        $img->setImageBackgroundColor('None');
        $w = $img->getImageWidth();
        $h = $img->getImageHeight();
        $img->extentImage(250, 250, ($w - 250) / 2, ($h - 250) / 2);
        $img->writeImage($targetThumb);
        unlink($file);
        //Attach featured image
        $wp_filetype = wp_check_filetype($pngfilename, null);
        $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($pngfilename), 'post_content' => '', 'post_status' => 'inherit');
        $attach_id = wp_insert_attachment($attachment, $targetThumb, $post_id);
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $targetThumb);
        wp_update_attachment_metadata($attach_id, $attach_data);
        set_post_thumbnail($post_id, $attach_id);
        // Otherwise, we'll stop
    } else {
        // Arbitrarily use -2 to indicate that the page with the title already exists
        $post_id = -2;
    }
    // end if
}
 /**
  * @param Thumbnail $thumbnail
  * @return void
  * @throws Exception\NoThumbnailAvailableException
  */
 public function refresh(Thumbnail $thumbnail)
 {
     try {
         $filenameWithoutExtension = pathinfo($thumbnail->getOriginalAsset()->getResource()->getFilename(), PATHINFO_FILENAME);
         $temporaryLocalCopyFilename = $thumbnail->getOriginalAsset()->getResource()->createTemporaryLocalCopy();
         $documentFile = sprintf(in_array($thumbnail->getOriginalAsset()->getResource()->getFileExtension(), $this->getOption('paginableDocuments')) ? '%s[0]' : '%s', $temporaryLocalCopyFilename);
         $width = $thumbnail->getConfigurationValue('width') ?: $thumbnail->getConfigurationValue('maximumWidth');
         $height = $thumbnail->getConfigurationValue('height') ?: $thumbnail->getConfigurationValue('maximumHeight');
         $im = new \Imagick();
         $im->setResolution($this->getOption('resolution'), $this->getOption('resolution'));
         $im->readImage($documentFile);
         $im->setImageFormat('png');
         $im->setImageBackgroundColor('white');
         $im->setImageCompose(\Imagick::COMPOSITE_OVER);
         $im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_RESET);
         $im->thumbnailImage($width, $height, true);
         $im->flattenImages();
         // Replace flattenImages in imagick 3.3.0
         // @see https://pecl.php.net/package/imagick/3.3.0RC2
         // $im->mergeImageLayers(\Imagick::LAYERMETHOD_MERGE);
         $resource = $this->resourceManager->importResourceFromContent($im->getImageBlob(), $filenameWithoutExtension . '.png');
         $im->destroy();
         $thumbnail->setResource($resource);
         $thumbnail->setWidth($width);
         $thumbnail->setHeight($height);
     } catch (\Exception $exception) {
         $filename = $thumbnail->getOriginalAsset()->getResource()->getFilename();
         $sha1 = $thumbnail->getOriginalAsset()->getResource()->getSha1();
         $message = sprintf('Unable to generate thumbnail for the given document (filename: %s, SHA1: %s)', $filename, $sha1);
         throw new Exception\NoThumbnailAvailableException($message, 1433109652, $exception);
     }
 }
Exemple #3
0
    /**
     * (non-PHPdoc)
     * @see Imagine\Image\ImagineInterface::create()
     */
    public function create(BoxInterface $size, Color $color = null)
    {
        $width  = $size->getWidth();
        $height = $size->getHeight();

        $color = null !== $color ? $color : new Color('fff');

        try {
            $pixel = new \ImagickPixel((string) $color);
            $pixel->setColorValue(
                \Imagick::COLOR_OPACITY,
                number_format(abs(round($color->getAlpha() / 100, 1)), 1)
            );

            $imagick = new \Imagick();
            $imagick->newImage($width, $height, $pixel);
            $imagick->setImageMatte(true);
            $imagick->setImageBackgroundColor($pixel);

            $pixel->clear();
            $pixel->destroy();

            return new Image($imagick);
        } catch (\ImagickException $e) {
            throw new RuntimeException(
                'Could not create empty image', $e->getCode(), $e
            );
        }
    }
Exemple #4
0
 public function save()
 {
     if (!$this->emptyAttr('id')) {
         $ecatalog = R::findOne('ecatalog', 'id=?', [$this->getAttr('id')]);
         $ecatalog->updated_at = date('Y-m-d H:i:s');
     } else {
         $ecatalog = R::dispense('ecatalog');
         $ecatalog->created_at = date('Y-m-d H:i:s');
         $ecatalog->updated_at = date('Y-m-d H:i:s');
         $ecatalog->sort_order = (int) R::getCell("SELECT MAX(sort_order) FROM ecatalog") + 1;
     }
     $ecatalog->name = $this->getAttr('name');
     $ecatalog->is_new = $this->getAttr('is_new');
     if (!$this->emptyAttr('pdf') && is_uploaded_file($this->attr['pdf']['tmp_name'])) {
         $pdf = $this->getAttr('pdf');
         $pdf_path = $this->generateName('ecatalog_pdf_') . '.pdf';
         $cover_path = $this->generateName('ecatalog_cover_') . '.jpeg';
         $im = new \Imagick($pdf['tmp_name'] . '[0]');
         $im->setImageBackgroundColor('white');
         // $im = $im->flattenImages();
         $im = $im->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
         $im->setImageFormat('jpeg');
         if ($im->getImageColorspace() == \Imagick::COLORSPACE_CMYK) {
             $im->setImageColorspace(\Imagick::COLORSPACE_SRGB);
         }
         $im->thumbnailImage(512, 0);
         $im->writeImage('upload/' . $cover_path);
         $im->clear();
         $im->destroy();
         move_uploaded_file($pdf['tmp_name'], 'upload/' . $pdf_path);
         $this->pushDeleteWhenSuccess('upload/' . $ecatalog->pdf_path);
         $this->pushDeleteWhenSuccess('upload/' . $ecatalog->cover_path);
         $this->pushDeleteWhenFailed('upload/' . $pdf_path);
         $this->pushDeleteWhenFailed('upload/' . $cover_path);
         $ecatalog->pdf_path = $pdf_path;
         $ecatalog->cover_path = $cover_path;
     }
     $success = R::store($ecatalog);
     if ($success) {
         $this->handlerSuccess();
     } else {
         $this->handlerFailed();
     }
     return $success;
 }
Exemple #5
0
 public function create(BoxInterface $size, ColorInterface $color = null)
 {
     $width = $size->getWidth();
     $height = $size->getHeight();
     $color = self::getColor($color);
     try {
         $pixel = new \ImagickPixel($color['color']);
         $pixel->setColorValue(\Imagick::COLOR_OPACITY, $color['alpha']);
         $magick = new \Imagick();
         $magick->newImage($width, $height, $pixel);
         $magick->setImageMatte(true);
         $magick->setImageBackgroundColor($pixel);
         $pixel->clear();
         $pixel->destroy();
         return new RImage($magick, $color['palette'], self::$emptyBag, array($width, $height));
     } catch (\Exception $e) {
         throw new \Imagine\Exception\RuntimeException("Imagick: Could not create empty image {$e->getMessage()}", $e->getCode(), $e);
     }
 }
Exemple #6
0
 /**
  * Generate a derivative image with Imagick.
  */
 public function createImage($sourcePath, $destPath, $type, $sizeConstraint, $mimeType)
 {
     $page = (int) $this->getOption('page', 0);
     try {
         $imagick = new Imagick($sourcePath . '[' . $page . ']');
     } catch (ImagickException $e) {
         _log("Imagick failed to open the file. Details:\n{$e}", Zend_Log::ERR);
         return false;
     }
     $origX = $imagick->getImageWidth();
     $origY = $imagick->getImageHeight();
     $imagick->setImagePage($origX, $origY, 0, 0);
     $imagick->setBackgroundColor('white');
     $imagick->setImageBackgroundColor('white');
     $imagick = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
     if ($type != 'square_thumbnail') {
         $imagick->thumbnailImage($sizeConstraint, $sizeConstraint, true);
     } else {
         // We could use cropThumbnailImage here but it lacks support for
         // the gravity setting
         if ($origX < $origY) {
             $newX = $sizeConstraint;
             $newY = $origY * ($sizeConstraint / $origX);
             $offsetX = 0;
             $offsetY = $this->_getCropOffsetY($newY, $sizeConstraint);
         } else {
             $newY = $sizeConstraint;
             $newX = $origX * ($sizeConstraint / $origY);
             $offsetY = 0;
             $offsetX = $this->_getCropOffsetX($newX, $sizeConstraint);
         }
         $imagick->thumbnailImage($newX, $newY);
         $imagick->cropImage($sizeConstraint, $sizeConstraint, $offsetX, $offsetY);
         $imagick->setImagePage($sizeConstraint, $sizeConstraint, 0, 0);
     }
     $imagick->writeImage($destPath);
     $imagick->clear();
     return true;
 }
 /**
  * Prepare the image for output, scaling and flattening as required
  *
  * @since 2.10
  * @uses self::$image updates the image in this Imagick object
  *
  * @param	integer	zero or new width
  * @param	integer	zero or new height
  * @param	boolean	proportional fit (true) or exact fit (false)
  * @param	string	output MIME type
  * @param	integer	compression quality; 1 - 100
  *
  * @return void
  */
 private static function _prepare_image($width, $height, $best_fit, $type, $quality)
 {
     if (is_callable(array(self::$image, 'scaleImage'))) {
         if (0 < $width && 0 < $height) {
             // Both are set; use them as-is
             self::$image->scaleImage($width, $height, $best_fit);
         } elseif (0 < $width || 0 < $height) {
             // One is set; scale the other one proportionally if reducing
             $image_size = self::$image->getImageGeometry();
             if ($width && isset($image_size['width']) && $width < $image_size['width']) {
                 self::$image->scaleImage($width, 0);
             } elseif ($height && isset($image_size['height']) && $height < $image_size['height']) {
                 self::$image->scaleImage(0, $height);
             }
         } else {
             // Neither is specified, apply defaults
             self::$image->scaleImage(150, 0);
         }
     }
     if (0 < $quality && 101 > $quality) {
         if ('image/jpeg' == $type) {
             self::$image->setImageCompressionQuality($quality);
             self::$image->setImageCompression(imagick::COMPRESSION_JPEG);
         } else {
             self::$image->setImageCompressionQuality($quality);
         }
     }
     if ('image/jpeg' == $type) {
         if (is_callable(array(self::$image, 'setImageBackgroundColor'))) {
             self::$image->setImageBackgroundColor('white');
         }
         if (is_callable(array(self::$image, 'mergeImageLayers'))) {
             self::$image = self::$image->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);
         } elseif (is_callable(array(self::$image, 'flattenImages'))) {
             self::$image = self::$image->flattenImages();
         }
     }
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function create(BoxInterface $size, ColorInterface $color = null)
 {
     $width = $size->getWidth();
     $height = $size->getHeight();
     $palette = null !== $color ? $color->getPalette() : new RGB();
     $color = null !== $color ? $color : $palette->color('fff');
     try {
         $pixel = new \ImagickPixel((string) $color);
         $pixel->setColorValue(Imagick::COLOR_ALPHA, $color->getAlpha() / 100);
         $imagick = new Imagick();
         $imagick->newImage($width, $height, $pixel);
         $imagick->setImageMatte(true);
         $imagick->setImageBackgroundColor($pixel);
         if (version_compare('6.3.1', $this->getVersion($imagick)) < 0) {
             $imagick->setImageOpacity($pixel->getColorValue(Imagick::COLOR_ALPHA));
         }
         $pixel->clear();
         $pixel->destroy();
         return new Image($imagick, $palette, new MetadataBag());
     } catch (\ImagickException $e) {
         throw new RuntimeException('Could not create empty image', $e->getCode(), $e);
     }
 }
 /**
  * function filter_render_type
  * Returns HTML markup containing an image with a data: URI
  * @param string $content The text to be rendered
  * @param string $font_file The path to a font file in a format ImageMagick can handle
  * @param integer $font_size The font size, in pixels (defaults to 28)
  * @param string $font_color The font color (defaults to 'black')
  * @param string $background_color The background color (defaults to 'transparent')
  * @param string $output_format The image format to use (defaults to 'png')
  * @return string HTML markup containing the rendered image
  **/
 public function filter_render_type($content, $font_file, $font_size, $font_color, $background_color, $output_format, $width)
 {
     // Preprocessing $content
     // 1. Strip HTML tags. It would be better to support them, but we just strip them for now.
     // 2. Decode HTML entities to UTF-8 charaaters.
     $content = html_entity_decode(strip_tags($content), ENT_QUOTES, 'UTF-8');
     // 3. Do word wrap when $width is specified. Not work for double-width characters.
     if (is_int($width)) {
         $content = wordwrap($content, floor($width / (0.3 * $font_size)));
     }
     $cache_group = strtolower(get_class($this));
     $cache_key = $font_file . $font_size . $font_color . $background_color . $output_format . $content . $width;
     if (!Cache::has(array($cache_group, md5($cache_key)))) {
         $font_color = new ImagickPixel($font_color);
         $background_color = new ImagickPixel($background_color);
         $draw = new ImagickDraw();
         $draw->setFont($font_file);
         $draw->setFontSize($font_size);
         $draw->setFillColor($font_color);
         $draw->setTextEncoding('UTF-8');
         $draw->annotation(0, $font_size * 2, $content);
         $canvas = new Imagick();
         $canvas->newImage(1000, $font_size * 5, $background_color);
         $canvas->setImageFormat($output_format);
         $canvas->drawImage($draw);
         // The following line ensures that the background color is set in the PNG
         // metadata, when using that format. This allows you, by specifying an RGBa
         // background color (e.g. #ffffff00) to create PNGs with a transparent background
         // for browsers that support it but with a "fallback" background color (the RGB
         // part of the RGBa color) for IE6, which does not support alpha in PNGs.
         $canvas->setImageBackgroundColor($background_color);
         $canvas->trimImage(0);
         Cache::set(array($cache_group, md5($cache_key)), $canvas->getImageBlob());
     }
     return '<img class="rendered-type" src="' . URL::get('display_rendertype', array('hash' => md5($cache_key), 'format' => $output_format)) . '" title="' . $content . '" alt="' . $content . '">';
 }
Exemple #10
0
 /**
  * @desc Create a thumbnail of the picture and save it
  * @param $size The size requested
  */
 private function createThumbnail($width, $height = false, $format = 'jpeg')
 {
     if (!in_array($format, array_keys($this->_formats))) {
         $format = 'jpeg';
     }
     if (!$height) {
         $height = $width;
     }
     $path = $this->_path . md5($this->_key) . '_' . $width . $this->_formats[$format];
     $im = new Imagick();
     try {
         $im->readImageBlob($this->_bin);
         $im->setImageFormat($format);
         if ($format == 'jpeg') {
             $im->setImageCompression(Imagick::COMPRESSION_JPEG);
             $im->setImageAlphaChannel(11);
             // Put 11 as a value for now, see http://php.net/manual/en/imagick.flattenimages.php#116956
             //$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
             $im->setImageBackgroundColor('#ffffff');
             $im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
         }
         //$crop = new CropEntropy;
         //$crop->setImage($im);
         $geo = $im->getImageGeometry();
         $im->cropThumbnailImage($width, $height);
         if ($width > $geo['width']) {
             $factor = floor($width / $geo['width']);
             $im->blurImage($factor, 10);
         }
         //$im = $crop->resizeAndCrop($width, $height);
         $im->setImageCompressionQuality(85);
         $im->setInterlaceScheme(Imagick::INTERLACE_PLANE);
         $im->writeImage($path);
         $im->clear();
     } catch (ImagickException $e) {
         error_log($e->getMessage());
     }
 }
 /**
  * Set the fill and margins of the image.
  * @param Imagick $method
  * @param string $colorKey
  * @param string $marginKey
  * @return Imagick
  * @access private
  * @final
  */
 private final function setColorAndMargin(Imagick $image, $colorKey = '', $marginKey = '')
 {
     if (isset($this->settings[$colorKey]) && empty($this->settings[$colorKey]) === false) {
         $image->setImageBackgroundColor("#{$this->settings[$colorKey]}");
         if (isset($this->settings[$marginKey]) && empty($this->settings[$marginKey]) === false && (int) $this->settings[$marginKey] <= 15) {
             $source = $image->getImageGeometry();
             $image->resizeImage($source['width'] - $this->settings[$marginKey] * 2, $source['height'] - $this->settings[$marginKey] * 2, Imagick::FILTER_CUBIC, 1);
             $image->borderImage("#{$this->settings[$colorKey]}", $this->settings[$marginKey], $this->settings[$marginKey]);
         }
     }
     return $image;
 }
Exemple #12
0
<?php

$im = new Imagick("magick:logo");
$im->setImageBackgroundColor("pink");
$im->thumbnailImage(200, 200, true, true);
$color = $im->getImagePixelColor(5, 5);
if ($color->isPixelSimilar("pink", 0)) {
    echo "Similar" . PHP_EOL;
} else {
    var_dump($color->getColorAsString());
}
$color = $im->getImagePixelColor(199, 5);
if ($color->isPixelSimilar("pink", 0)) {
    echo "Similar" . PHP_EOL;
} else {
    var_dump($color->getColorAsString());
}
Exemple #13
0
 protected function _background($r, $g, $b, $opacity)
 {
     $color = sprintf("rgb(%d, %d, %d)", $r, $g, $b);
     $pixel1 = new \ImagickPixel($color);
     $opacity = $opacity / 100;
     $pixel2 = new \ImagickPixel("transparent");
     $background = new \Imagick();
     $this->_image->setIteratorIndex(0);
     while (true) {
         $background->newImage($this->_width, $this->_height, $pixel1);
         if (!$background->getImageAlphaChannel()) {
             $background->setImageAlphaChannel(constant("Imagick::ALPHACHANNEL_SET"));
         }
         $background->setImageBackgroundColor($pixel2);
         $background->evaluateImage(constant("Imagick::EVALUATE_MULTIPLY"), $opacity, constant("Imagick::CHANNEL_ALPHA"));
         $background->setColorspace($this->_image->getColorspace());
         $background->compositeImage($this->_image, constant("Imagick::COMPOSITE_DISSOLVE"), 0, 0);
         if (!$this->_image->nextImage()) {
             break;
         }
     }
     $this->_image->clear();
     $this->_image->destroy();
     $this->_image = $background;
 }
Exemple #14
0
 /**
  * Draws the shadow of the card
  */
 public function drawShadow($hexColour)
 {
     $onlineIndicator = isset($_GET['onlineindicator']) ? $_GET['onlineindicator'] : false;
     $online = $onlineIndicator == 1 || $onlineIndicator == 3 ? Utils::isUserOnline($this->user['username']) : false;
     $colour = $online ? new ImagickPixel($hexColour) : new ImagickPixel('black');
     $shadow = new Imagick();
     $shadow->newImage($this->canvas->getImageWidth(), $this->canvas->getImageHeight(), new ImagickPixel('transparent'));
     $shadow->setImageBackgroundColor($colour);
     $shadowArea = new ImagickDraw();
     $shadowArea->setFillColor($colour);
     $shadowArea->roundRectangle(0, 0, $this->baseWidth - 1, $this->baseHeight - 2, self::SIG_ROUNDING, self::SIG_ROUNDING);
     $shadow->drawImage($shadowArea);
     $shadow->shadowImage($online ? 40 : 15, 1.5, 0, 0);
     $this->canvas->compositeImage($shadow, Imagick::COMPOSITE_DEFAULT, 0, 1);
 }
Exemple #15
0
}
// Check token
if (!ValidPost()) {
    ServerError("Invalid post request.");
}
// Convert SVG string to image
if (class_exists("Imagick")) {
    // Use Imagick if available
    try {
        $img = new Imagick();
        $svg = '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . ewr_StripSlashes(@$_POST["stream"]);
        // Get SVG string
        // Replace, for example, fill="url('#10-270-rgba_255_0_0_1_-rgba_255_255_255_1_')" by fill="rgb(255, 0, 0)"
        $svg = preg_replace('/fill="url\\(\'#[\\w-]+rgba_(\\d+)_(\\d+)_(\\d+)_(\\d+)_-[\\w-]+\'\\)"/', 'fill="rgb($1, $2, $3)"', $svg);
        $img->readImageBlob($svg);
        $img->setImageBackgroundColor(new ImagickPixel("transparent"));
        $img->setImageFormat("png24");
    } catch (Exception $e) {
        ServerError($e->getMessage());
    }
} elseif (function_exists("curl_init")) {
    // Use export.api3.fusioncharts.com and curl
    $postdata = file_get_contents("php://input");
    // Get POST data
    $img = ewr_ClientUrl("export.api3.fusioncharts.com", $postdata, "POST");
    // Get the chart from fusioncharts.com
    if ($img === FALSE) {
        ServerError("Failed to get chart image from export server. Make sure your web server is online.");
    }
} else {
    ServerError("Both Imagick and cURL not installed on this server.");
 private function convert_png_to_jpg($input_path, $remove_input = true)
 {
     $output_path = str_replace(".png", ".jpg", $input_path);
     // create new imagick object from image.jpg
     $im = new Imagick($input_path);
     $im->setImageBackgroundColor('white');
     $im = $im->flattenImages();
     $im->setImageFormat("jpg");
     $im->writeImage($output_path);
     if ($remove_input) {
         unlink($input_path);
     }
     return $output_path;
 }
Exemple #17
0
 /**
  * Fill the image background.
  * @param integer $r
  * @param integer $g
  * @param integer $b
  * @param integer $opacity
  */
 protected function _background($r, $g, $b, $opacity)
 {
     $background = new \Imagick();
     $background->newImage($this->width, $this->height, new \ImagickPixel(sprintf('rgb(%d, %d, %d)', $r, $g, $b)));
     if (!$background->getImageAlphaChannel()) {
         $background->setImageAlphaChannel(\Imagick::ALPHACHANNEL_SET);
     }
     $background->setImageBackgroundColor(new \ImagickPixel('transparent'));
     $background->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity / 100, \Imagick::CHANNEL_ALPHA);
     $background->setColorspace($this->im->getColorspace());
     if ($background->compositeImage($this->im, \Imagick::COMPOSITE_DISSOLVE, 0, 0)) {
         $this->im = $background;
     }
 }
Exemple #18
0
 /**
  * Applies the effect.
  */
 public function apply()
 {
     $i = 1;
     $cnt = count($this->_params['images']);
     if ($cnt <= 0) {
         throw new Horde_Image_Exception('No Images provided.');
     }
     if (!method_exists($this->_image->imagick, 'polaroidImage') || !method_exists($this->_image->imagick, 'trimImage')) {
         throw new Horde_Image_Exception('Your version of Imagick is not compiled against a recent enough ImageMagick library to use the PhotoStack effect.');
     }
     $imgs = array();
     $length = 0;
     try {
         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 Imagick();
                 $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 Imagick();
                     $imgk->clear();
                     $imgk->readImageBlob($image->raw());
                     // Either resize the thumbnail to match the top image or we
                     // *are* the top image already.
                     if ($i++ <= $cnt) {
                         $imgk->thumbnailImage($size['width'], $size['height'], false);
                     } else {
                         $imgk->destroy();
                         $imgk = $topimg->clone();
                     }
                     if ($this->_params['type'] == 'rounded') {
                         $imgk = $this->_roundBorder($imgk);
                     } else {
                         $imgk->borderImage($this->_params['bordercolor'], $this->_params['borderwidth'], $this->_params['borderwidth']);
                     }
                     // Only shadow the bottom image for 'plain' stacks
                     if (!$haveBottom) {
                         $shad = $imgk->clone();
                         $shad->setImageBackgroundColor(new ImagickPixel('black'));
                         $shad->shadowImage(80, 4, 0, 0);
                         $shad->compositeImage($imgk, 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) {
                     // @TODO: instead of doing $image->raw(), we might be able
                     //        to clone the imagick object if we can do it
                     //        cleanly might be faster, less memory intensive?
                     $imgk = new Imagick();
                     $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(new ImagickDraw(), $angle);
                     // 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, Imagick::COMPOSITE_OVER, $xo, $yo);
             $image->removeImage();
             $image->destroy();
         }
         // Trim the canvas before resizing to keep the thumbnails as large
         // as possible.
         $this->_image->imagick->trimImage(0);
         if ($this->_params['padding'] || $this->_params['background'] != 'none') {
             $this->_image->imagick->borderImage(new ImagickPixel($this->_params['background']), $this->_params['padding'], $this->_params['padding']);
         }
     } catch (ImagickPixelException $e) {
         throw new Horde_Image_Exception($e);
     } catch (ImagickException $e) {
         throw new Horde_Image_Exception($e);
     }
 }
 protected function upload_image($img, $servercheck = null)
 {
     $image = new \Imagick($img['tmp_name']);
     $image->setImageBackgroundColor('white');
     // Entfernt Transparenz bein png's
     $image->scaleImage(800, 400, true);
     $image = $image->flattenImages();
     // Deprecated!
     $image->setImageCompressionQuality(90);
     // = Idealer Wert???
     $image->setImageFormat('jpg');
     // see also: $image->getImageFormat();
     if ($_SERVER['SERVER_NAME'] == "localhost") {
         $image->writeImage($this->localbildpfad . substr(md5($img['name']), 0, 18) . '.jpg');
     } elseif ($_SERVER['SERVER_NAME'] == "test.leipziger-ecken.de") {
         $image->writeImage($this->testbildpfad . substr(md5($img['name']), 0, 18) . '.jpg');
     } else {
         $image->writeImage($this->bildpfad . substr(md5($img['name']), 0, 18) . '.jpg');
     }
     return base_path() . $this->short_bildpfad . substr(md5($img['name']), 0, 18) . '.jpg';
 }
 /**
  * Convert a transparent PNG to JPG, with specified background color
  *
  * @param string $id Attachment ID
  * @param string $file File Path Original Image
  * @param string $meta Attachment Meta
  * @param string $size Image size. set to 'full' by default
  *
  * @return array Savings and Updated Meta
  */
 function convert_tpng_to_jpg($id = '', $file = '', $meta = '', $size = 'full')
 {
     global $wpsmush_settings;
     $result = array('meta' => $meta, 'savings' => '');
     //Flag: Whether the image was converted or not
     if ('full' == $size) {
         $result['converted'] = false;
     }
     //If any of the values is not set
     if (empty($id) || empty($file) || empty($meta)) {
         return $result;
     }
     //Get the File name without ext
     $n_file = pathinfo($file);
     if (empty($n_file['dirname']) || empty($n_file['filename'])) {
         return $result;
     }
     $n_file['filename'] = wp_unique_filename($n_file['dirname'], $n_file['filename'] . '.jpg');
     //Updated File name
     $n_file = path_join($n_file['dirname'], $n_file['filename']);
     $transparent_png = $wpsmush_settings->get_setting(WP_SMUSH_PREFIX . 'transparent_png');
     /**
      * Filter Background Color for Transparent PNGs
      */
     $bg = apply_filters('wp_smush_bg', $transparent_png['background'], $id, $size);
     $quality = $this->get_quality($file);
     if ($this->supports_imagick()) {
         try {
             $imagick = new Imagick($file);
             $imagick->setImageBackgroundColor(new ImagickPixel('#' . $bg));
             $imagick->setImageAlphaChannel(11);
             $imagick->setImageFormat('JPG');
             $imagick->setCompressionQuality($quality);
             $imagick->writeImage($n_file);
         } catch (Exception $e) {
             error_log("WP Smush PNG to JPG Conversion error in " . __FILE__ . " at " . __LINE__ . " " . $e->getMessage());
             return $result;
         }
     } else {
         //Use GD for conversion
         //Get data from PNG
         $input = imagecreatefrompng($file);
         //Width and Height of image
         list($width, $height) = getimagesize($file);
         //Create New image
         $output = imagecreatetruecolor($width, $height);
         // set background color for GD
         $r = hexdec('0x' . strtoupper(substr($bg, 0, 2)));
         $g = hexdec('0x' . strtoupper(substr($bg, 2, 2)));
         $b = hexdec('0x' . strtoupper(substr($bg, 4, 2)));
         //Set the Background color
         $rgb = imagecolorallocate($output, $r, $g, $b);
         //Fill Background
         imagefilledrectangle($output, 0, 0, $width, $height, $rgb);
         //Create New image
         imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
         //Create JPG
         imagejpeg($output, $n_file, $quality);
     }
     //Replace file, and get savings
     $result = $this->replace_file($file, $result, $n_file);
     if (!empty($result['savings'])) {
         if ('full' == $size) {
             $result['converted'] = true;
         }
         //Update the File Details. and get updated meta
         $result['meta'] = $this->update_image_path($id, $file, $n_file, $meta, $size);
         /**
          *  Perform a action after the image URL is updated in post content
          */
         do_action('wp_smush_image_url_changed', $id, $file, $n_file, $size);
     }
     return $result;
 }
/**
 * Process an image.
 *
 * Returns an array of the $file, $results, $converted to tell us if an image changes formats, and the $original file if it did.
 *
 * @param   string $file		Full absolute path to the image file
 * @param   int $gallery_type		1=wordpress, 2=nextgen, 3=flagallery, 4=aux_images, 5=image editor, 6=imagestore
 * @param   boolean $converted		tells us if this is a resize and the full image was converted to a new format
 * @param   boolean $new		tells the optimizer that this is a new image, so it should attempt conversion regardless of previous results
 * @param   boolean $fullsize		tells the optimizer this is a full size image
 * @returns array
 */
function ewww_image_optimizer($file, $gallery_type = 4, $converted = false, $new = false, $fullsize = false)
{
    ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>');
    // if the plugin gets here without initializing, we need to run through some things first
    if (!defined('EWWW_IMAGE_OPTIMIZER_CLOUD')) {
        ewww_image_optimizer_cloud_init();
    }
    session_write_close();
    $bypass_optimization = apply_filters('ewww_image_optimizer_bypass', false, $file);
    if (true === $bypass_optimization) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $file);
    }
    // initialize the original filename
    $original = $file;
    $result = '';
    // check that the file exists
    if (FALSE === file_exists($file)) {
        // tell the user we couldn't find the file
        $msg = sprintf(__('Could not find %s', EWWW_IMAGE_OPTIMIZER_DOMAIN), $file);
        ewwwio_debug_message("file doesn't appear to exist: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $original);
    }
    // check that the file is writable
    if (FALSE === is_writable($file)) {
        // tell the user we can't write to the file
        $msg = sprintf(__('%s is not writable', EWWW_IMAGE_OPTIMIZER_DOMAIN), $file);
        ewwwio_debug_message("couldn't write to the file {$file}");
        // send back the above message
        return array(false, $msg, $converted, $original);
    }
    if (function_exists('fileperms')) {
        $file_perms = substr(sprintf('%o', fileperms($file)), -4);
    }
    $file_owner = 'unknown';
    $file_group = 'unknown';
    if (function_exists('posix_getpwuid')) {
        $file_owner = posix_getpwuid(fileowner($file));
        $file_owner = $file_owner['name'];
    }
    if (function_exists('posix_getgrgid')) {
        $file_group = posix_getgrgid(filegroup($file));
        $file_group = $file_group['name'];
    }
    ewwwio_debug_message("permissions: {$file_perms}, owner: {$file_owner}, group: {$file_group}");
    $type = ewww_image_optimizer_mimetype($file, 'i');
    if (strpos($type, 'image') === FALSE && strpos($type, 'pdf') === FALSE) {
        ewwwio_debug_message('could not find any functions for mimetype detection');
        //otherwise we store an error message since we couldn't get the mime-type
        return array(false, __('Unknown type: ' . $type, EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
        $msg = __('Missing finfo_file(), getimagesize() and mime_content_type() PHP functions', EWWW_IMAGE_OPTIMIZER_DOMAIN);
        return array(false, $msg, $converted, $original);
    }
    if (!EWWW_IMAGE_OPTIMIZER_CLOUD) {
        // check to see if 'nice' exists
        $nice = ewww_image_optimizer_find_nix_binary('nice', 'n');
        if (!defined('EWWW_IMAGE_OPTIMIZER_NOEXEC')) {
            // Check if exec is disabled
            if (ewww_image_optimizer_exec_check()) {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', true);
                ewwwio_debug_message('exec seems to be disabled');
                ewww_image_optimizer_disable_tools();
                // otherwise, query the php settings for safe mode
            } elseif (ewww_image_optimizer_safemode_check()) {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', true);
                ewwwio_debug_message('safe mode appears to be enabled');
                ewww_image_optimizer_disable_tools();
            } else {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', false);
            }
        }
    }
    $skip = ewww_image_optimizer_skip_tools();
    // if the user has disabled the utility checks
    if (EWWW_IMAGE_OPTIMIZER_CLOUD) {
        $skip['jpegtran'] = true;
        $skip['optipng'] = true;
        $skip['gifsicle'] = true;
        $skip['pngout'] = true;
        $skip['pngquant'] = true;
        $skip['webp'] = true;
    }
    if (ewww_image_optimizer_get_option('ewww_image_optimizer_metadata_skip_full') && $fullsize) {
        $keep_metadata = true;
    } else {
        $keep_metadata = false;
    }
    if (ewww_image_optimizer_get_option('ewww_image_optimizer_lossy_skip_full') && $fullsize) {
        $skip_lossy = true;
    } else {
        $skip_lossy = false;
    }
    if (ini_get('max_execution_time') < 90 && ewww_image_optimizer_stl_check()) {
        set_time_limit(0);
    }
    // if the full-size image was converted
    if ($converted) {
        ewwwio_debug_message('full-size image was converted, need to rebuild filename for meta');
        $filenum = $converted;
        // grab the file extension
        preg_match('/\\.\\w+$/', $file, $fileext);
        // strip the file extension
        $filename = str_replace($fileext[0], '', $file);
        // grab the dimensions
        preg_match('/-\\d+x\\d+(-\\d+)*$/', $filename, $fileresize);
        // strip the dimensions
        $filename = str_replace($fileresize[0], '', $filename);
        // reconstruct the filename with the same increment (stored in $converted) as the full version
        $refile = $filename . '-' . $filenum . $fileresize[0] . $fileext[0];
        // rename the file
        rename($file, $refile);
        ewwwio_debug_message("moved {$file} to {$refile}");
        // and set $file to the new filename
        $file = $refile;
        $original = $file;
    }
    // get the original image size
    $orig_size = filesize($file);
    ewwwio_debug_message("original filesize: {$orig_size}");
    if ($orig_size < ewww_image_optimizer_get_option('ewww_image_optimizer_skip_size')) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed due to filesize: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $file);
    }
    if ($type == 'image/png' && ewww_image_optimizer_get_option('ewww_image_optimizer_skip_png_size') && $orig_size > ewww_image_optimizer_get_option('ewww_image_optimizer_skip_png_size')) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed due to filesize: {$file}");
        // send back the above message
        return array($file, $msg, $converted, $file);
    }
    // initialize $new_size with the original size, HOW ABOUT A ZERO...
    //$new_size = $orig_size;
    $new_size = 0;
    // set the optimization process to OFF
    $optimize = false;
    // toggle the convert process to ON
    $convert = true;
    // allow other plugins to mangle the image however they like prior to optimization
    do_action('ewww_image_optimizer_pre_optimization', $file, $type);
    // run the appropriate optimization/conversion for the mime-type
    switch ($type) {
        case 'image/jpeg':
            $png_size = 0;
            // if jpg2png conversion is enabled, and this image is in the wordpress media library
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_to_png') && $gallery_type == 1 || !empty($_GET['ewww_convert'])) {
                // generate the filename for a PNG
                // if this is a resize version
                if ($converted) {
                    // just change the file extension
                    $pngfile = preg_replace('/\\.\\w+$/', '.png', $file);
                    // if this is a full size image
                } else {
                    // get a unique filename for the png image
                    list($pngfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.png');
                }
            } else {
                // otherwise, set it to OFF
                $convert = false;
                $pngfile = '';
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') > 10) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $pngfile, 'image/png', $skip_lossy);
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/png', null, $orig_size != $new_size);
                } else {
                    ewww_image_optimizer_webp_create($file, $new_size, $type, null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], false, false, false, false, !$skip['webp']);
            }
            // if jpegtran optimization is disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') == 0) {
                // store an appropriate message in $result
                $result = __('JPG optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // otherwise, if we aren't skipping the utility verification and jpegtran doesn't exist
            } elseif (!$skip['jpegtran'] && !$tools['JPEGTRAN']) {
                // store an appropriate message in $result
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>jpegtran</em>');
                // otherwise, things should be good, so...
            } else {
                // set the optimization process to ON
                $optimize = true;
            }
            // if optimization is turned ON
            if ($optimize) {
                ewwwio_debug_message('attempting to optimize JPG...');
                // generate temporary file-names:
                $tempfile = $file . ".tmp";
                //non-progressive jpeg
                $progfile = $file . ".prog";
                // progressive jpeg
                // check to see if we are supposed to strip metadata (badly named)
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && !$keep_metadata) {
                    // don't copy metadata
                    $copy_opt = 'none';
                } else {
                    // copy all the metadata
                    $copy_opt = 'all';
                }
                // run jpegtran - non-progressive
                exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -outfile " . ewww_image_optimizer_escapeshellarg($tempfile) . " " . ewww_image_optimizer_escapeshellarg($file));
                // run jpegtran - progressive
                exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -progressive -outfile " . ewww_image_optimizer_escapeshellarg($progfile) . " " . ewww_image_optimizer_escapeshellarg($file));
                // check the filesize of the non-progressive JPG
                $non_size = ewww_image_optimizer_filesize($tempfile);
                // check the filesize of the progressive JPG
                $prog_size = ewww_image_optimizer_filesize($progfile);
                ewwwio_debug_message("optimized JPG (non-progresive) size: {$non_size}");
                ewwwio_debug_message("optimized JPG (progresive) size: {$prog_size}");
                if ($non_size === false || $prog_size === false) {
                    $result = __('Unable to write file', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                    $new_size = 0;
                } elseif (!$non_size || !$prog_size) {
                    $result = __('Optimization failed', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                    $new_size = 0;
                } else {
                    // if the progressive file is bigger
                    if ($prog_size > $non_size) {
                        // store the size of the non-progessive JPG
                        $new_size = $non_size;
                        if (is_file($progfile)) {
                            // delete the progressive file
                            unlink($progfile);
                        }
                        // if the progressive file is smaller or the same
                    } else {
                        // store the size of the progressive JPG
                        $new_size = $prog_size;
                        // replace the non-progressive with the progressive file
                        rename($progfile, $tempfile);
                    }
                }
                ewwwio_debug_message("optimized JPG size: {$new_size}");
                // if the best-optimized is smaller than the original JPG, and we didn't create an empty JPG
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller JPG
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both turned OFF, finish the JPG processing
            } elseif (!$convert) {
                ewww_image_optimizer_webp_create($file, $orig_size, $type, $tools['WEBP']);
                break;
            }
            // if the conversion process is turned ON, or if this is a resize and the full-size was converted
            if ($convert) {
                ewwwio_debug_message("attempting to convert JPG to PNG: {$pngfile}");
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                // convert the JPG to PNG
                if (ewww_image_optimizer_gmagick_support()) {
                    try {
                        $gmagick = new Gmagick($file);
                        $gmagick->stripimage();
                        $gmagick->setimageformat('PNG');
                        $gmagick->writeimage($pngfile);
                    } catch (Exception $gmagick_error) {
                        ewwwio_debug_message($gmagick_error->getMessage());
                    }
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                if (!$png_size && ewww_image_optimizer_imagick_support()) {
                    try {
                        $imagick = new Imagick($file);
                        $imagick->stripImage();
                        $imagick->setImageFormat('PNG');
                        $imagick->writeImage($pngfile);
                    } catch (Exception $imagick_error) {
                        ewwwio_debug_message($imagick_error->getMessage());
                    }
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                if (!$png_size) {
                    $convert_path = '';
                    // retrieve version info for ImageMagick
                    if (PHP_OS != 'WINNT') {
                        $convert_path = ewww_image_optimizer_find_nix_binary('convert', 'i');
                    } elseif (PHP_OS == 'WINNT') {
                        $convert_path = ewww_image_optimizer_find_win_binary('convert', 'i');
                    }
                    if (!empty($convert_path)) {
                        ewwwio_debug_message('converting with ImageMagick');
                        exec($convert_path . " " . ewww_image_optimizer_escapeshellarg($file) . " -strip " . ewww_image_optimizer_escapeshellarg($pngfile));
                        $png_size = ewww_image_optimizer_filesize($pngfile);
                    }
                }
                if (!$png_size && ewww_image_optimizer_gd_support()) {
                    ewwwio_debug_message('converting with GD');
                    imagepng(imagecreatefromjpeg($file), $pngfile);
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                // if lossy optimization is ON and full-size exclusion is not active
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 40 && $tools['PNGQUANT'] && !$skip_lossy) {
                    ewwwio_debug_message('attempting lossy reduction');
                    exec("{$nice} " . $tools['PNGQUANT'] . " " . ewww_image_optimizer_escapeshellarg($pngfile));
                    $quantfile = preg_replace('/\\.\\w+$/', '-fs8.png', $pngfile);
                    if (is_file($quantfile) && filesize($pngfile) > filesize($quantfile)) {
                        ewwwio_debug_message("lossy reduction is better: original - " . filesize($pngfile) . " vs. lossy - " . filesize($quantfile));
                        rename($quantfile, $pngfile);
                    } elseif (is_file($quantfile)) {
                        ewwwio_debug_message("lossy reduction is worse: original - " . filesize($pngfile) . " vs. lossy - " . filesize($quantfile));
                        unlink($quantfile);
                    } else {
                        ewwwio_debug_message('pngquant did not produce any output');
                    }
                }
                // if optipng isn't disabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng')) {
                    // retrieve the optipng optimization level
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // if the PNG file was created
                    if (file_exists($pngfile)) {
                        ewwwio_debug_message('optimizing converted PNG with optipng');
                        // run optipng on the new PNG
                        exec("{$nice} " . $tools['OPTIPNG'] . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                // if pngout isn't disabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout')) {
                    // retrieve the pngout optimization level
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // if the PNG file was created
                    if (file_exists($pngfile)) {
                        ewwwio_debug_message('optimizing converted PNG with pngout');
                        // run pngout on the new PNG
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                $png_size = ewww_image_optimizer_filesize($pngfile);
                ewwwio_debug_message("converted PNG size: {$png_size}");
                // if the PNG is smaller than the original JPG, and we didn't end up with an empty file
                if ($new_size > $png_size && $png_size != 0 && ewww_image_optimizer_mimetype($pngfile, 'i') == 'image/png') {
                    ewwwio_debug_message("converted PNG is better: {$png_size} vs. {$new_size}");
                    // store the size of the converted PNG
                    $new_size = $png_size;
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($file);
                    }
                    // store the location of the PNG file
                    $file = $pngfile;
                    // let webp know what we're dealing with now
                    $type = 'image/png';
                    // successful conversion and we store the increment
                    $converted = $filenum;
                } else {
                    ewwwio_debug_message('converted PNG is no good');
                    // otherwise delete the PNG
                    $converted = FALSE;
                    if (is_file($pngfile)) {
                        unlink($pngfile);
                    }
                }
            }
            ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
            break;
        case 'image/png':
            $jpg_size = 0;
            // png2jpg conversion is turned on, and the image is in the wordpress media library
            if ((ewww_image_optimizer_get_option('ewww_image_optimizer_png_to_jpg') || !empty($_GET['ewww_convert'])) && $gallery_type == 1 && !$skip_lossy && (!ewww_image_optimizer_png_alpha($file) || ewww_image_optimizer_jpg_background())) {
                ewwwio_debug_message('PNG to JPG conversion turned on');
                // if the user set a fill background for transparency
                $background = '';
                if ($background = ewww_image_optimizer_jpg_background()) {
                    // set background color for GD
                    $r = hexdec('0x' . strtoupper(substr($background, 0, 2)));
                    $g = hexdec('0x' . strtoupper(substr($background, 2, 2)));
                    $b = hexdec('0x' . strtoupper(substr($background, 4, 2)));
                    // set the background flag for 'convert'
                    $background = "-background " . '"' . "#{$background}" . '"';
                } else {
                    $r = '';
                    $g = '';
                    $b = '';
                }
                // if the user manually set the JPG quality
                if ($quality = ewww_image_optimizer_jpg_quality()) {
                    // set the quality for GD
                    $gquality = $quality;
                    // set the quality flag for 'convert'
                    $cquality = "-quality {$quality}";
                } else {
                    $cquality = '';
                    $gquality = '92';
                }
                // if this is a resize version
                if ($converted) {
                    // just replace the file extension with a .jpg
                    $jpgfile = preg_replace('/\\.\\w+$/', '.jpg', $file);
                    // if this is a full version
                } else {
                    // construct the filename for the new JPG
                    list($jpgfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.jpg');
                }
            } else {
                ewwwio_debug_message('PNG to JPG conversion turned off');
                // turn the conversion process OFF
                $convert = false;
                $jpgfile = '';
                $r = null;
                $g = null;
                $b = null;
                $gquality = null;
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') >= 20 && ewww_image_optimizer_get_option('ewww_image_optimizer_cloud_key')) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $jpgfile, 'image/jpeg', $skip_lossy, array('r' => $r, 'g' => $g, 'b' => $b, 'quality' => $gquality));
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/jpeg', null, $orig_size != $new_size);
                } else {
                    ewww_image_optimizer_webp_create($file, $new_size, $type, null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(false, !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            }
            // if pngout and optipng are disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng') && ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout') || ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 0) {
                // tell the user all PNG tools are disabled
                $result = __('PNG optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // if the utility checking is on, optipng is enabled, but optipng cannot be found
            } elseif (!$skip['optipng'] && !$tools['OPTIPNG']) {
                // tell the user optipng is missing
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>optipng</em>');
                // if the utility checking is on, pngout is enabled, but pngout cannot be found
            } elseif (!$skip['pngout'] && !$tools['PNGOUT']) {
                // tell the user pngout is missing
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>pngout</em>');
            } else {
                // turn optimization on if we made it through all the checks
                $optimize = true;
            }
            // if optimization is turned on
            if ($optimize) {
                // if lossy optimization is ON and full-size exclusion is not active
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 40 && $tools['PNGQUANT'] && !$skip_lossy) {
                    ewwwio_debug_message('attempting lossy reduction');
                    exec("{$nice} " . $tools['PNGQUANT'] . " " . ewww_image_optimizer_escapeshellarg($file));
                    $quantfile = preg_replace('/\\.\\w+$/', '-fs8.png', $file);
                    if (is_file($quantfile) && filesize($file) > filesize($quantfile) && ewww_image_optimizer_mimetype($quantfile, 'i') == $type) {
                        ewwwio_debug_message("lossy reduction is better: original - " . filesize($file) . " vs. lossy - " . filesize($quantfile));
                        rename($quantfile, $file);
                    } elseif (is_file($quantfile)) {
                        ewwwio_debug_message("lossy reduction is worse: original - " . filesize($file) . " vs. lossy - " . filesize($quantfile));
                        unlink($quantfile);
                    } else {
                        ewwwio_debug_message('pngquant did not produce any output');
                    }
                }
                $tempfile = $file . '.tmp.png';
                copy($file, $tempfile);
                // if optipng is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng')) {
                    // retrieve the optimization level for optipng
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // run optipng on the PNG file
                    exec("{$nice} " . $tools['OPTIPNG'] . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($tempfile));
                }
                // if pngout is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout')) {
                    // retrieve the optimization level for pngout
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // run pngout on the PNG file
                    exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($tempfile));
                }
                // retrieve the filesize of the temporary PNG
                $new_size = ewww_image_optimizer_filesize($tempfile);
                // if the new PNG is smaller
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller PNG
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both disabled we are done here
            } elseif (!$convert) {
                ewwwio_debug_message('calling webp, but neither convert or optimize');
                ewww_image_optimizer_webp_create($file, $orig_size, $type, $tools['WEBP']);
                break;
            }
            // retrieve the new filesize of the PNG
            $new_size = ewww_image_optimizer_filesize($file);
            // if conversion is on and the PNG doesn't have transparency or the user set a background color to replace transparency
            //if ( $convert && ( ! ewww_image_optimizer_png_alpha( $file ) || ewww_image_optimizer_jpg_background() ) ) {
            if ($convert) {
                ewwwio_debug_message("attempting to convert PNG to JPG: {$jpgfile}");
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                $magick_background = ewww_image_optimizer_jpg_background();
                if (empty($magick_background)) {
                    $magick_background = '000000';
                }
                // convert the PNG to a JPG with all the proper options
                if (ewww_image_optimizer_gmagick_support()) {
                    try {
                        if (ewww_image_optimizer_png_alpha($file)) {
                            $gmagick_overlay = new Gmagick($file);
                            $gmagick = new Gmagick();
                            $gmagick->newimage($gmagick_overlay->getimagewidth(), $gmagick_overlay->getimageheight(), '#' . $magick_background);
                            $gmagick->compositeimage($gmagick_overlay, 1, 0, 0);
                        } else {
                            $gmagick = new Gmagick($file);
                        }
                        $gmagick->setimageformat('JPG');
                        $gmagick->setcompressionquality($gquality);
                        $gmagick->writeimage($jpgfile);
                    } catch (Exception $gmagick_error) {
                        ewwwio_debug_message($gmagick_error->getMessage());
                    }
                    $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                }
                if (!$jpg_size && ewww_image_optimizer_imagick_support()) {
                    try {
                        $imagick = new Imagick($file);
                        if (ewww_image_optimizer_png_alpha($file)) {
                            $imagick->setImageBackgroundColor(new ImagickPixel('#' . $magick_background));
                            $imagick->setImageAlphaChannel(11);
                        }
                        $imagick->setImageFormat('JPG');
                        $imagick->setCompressionQuality($gquality);
                        $imagick->writeImage($jpgfile);
                    } catch (Exception $imagick_error) {
                        ewwwio_debug_message($imagick_error->getMessage());
                    }
                    $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                }
                if (!$jpg_size) {
                    // retrieve version info for ImageMagick
                    $convert_path = ewww_image_optimizer_find_nix_binary('convert', 'i');
                    if (!empty($convert_path)) {
                        ewwwio_debug_message('converting with ImageMagick');
                        ewwwio_debug_message("using command: {$convert_path} {$background} -alpha remove {$cquality} {$file} {$jpgfile}");
                        exec("{$convert_path} {$background} -alpha remove {$cquality} " . ewww_image_optimizer_escapeshellarg($file) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                        $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                    }
                }
                if (!$jpg_size && ewww_image_optimizer_gd_support()) {
                    ewwwio_debug_message('converting with GD');
                    // retrieve the data from the PNG
                    $input = imagecreatefrompng($file);
                    // retrieve the dimensions of the PNG
                    list($width, $height) = getimagesize($file);
                    // create a new image with those dimensions
                    $output = imagecreatetruecolor($width, $height);
                    if ($r === '') {
                        $r = 255;
                        $g = 255;
                        $b = 255;
                    }
                    // allocate the background color
                    $rgb = imagecolorallocate($output, $r, $g, $b);
                    // fill the new image with the background color
                    imagefilledrectangle($output, 0, 0, $width, $height, $rgb);
                    // copy the original image to the new image
                    imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
                    // output the JPG with the quality setting
                    imagejpeg($output, $jpgfile, $gquality);
                }
                $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                if ($jpg_size) {
                    ewwwio_debug_message("converted JPG filesize: {$jpg_size}");
                } else {
                    ewwwio_debug_message('unable to convert to JPG');
                }
                // next we need to optimize that JPG if jpegtran is enabled
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') == 10 && file_exists($jpgfile)) {
                    // generate temporary file-names:
                    $tempfile = $jpgfile . ".tmp";
                    //non-progressive jpeg
                    $progfile = $jpgfile . ".prog";
                    // progressive jpeg
                    // check to see if we are supposed to strip metadata (badly named)
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && !$keep_metadata) {
                        // don't copy metadata
                        $copy_opt = 'none';
                    } else {
                        // copy all the metadata
                        $copy_opt = 'all';
                    }
                    // run jpegtran - non-progressive
                    exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -outfile " . ewww_image_optimizer_escapeshellarg($tempfile) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                    // run jpegtran - progressive
                    exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -progressive -outfile " . ewww_image_optimizer_escapeshellarg($progfile) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                    // check the filesize of the non-progressive JPG
                    $non_size = ewww_image_optimizer_filesize($tempfile);
                    ewwwio_debug_message("non-progressive JPG filesize: {$non_size}");
                    // check the filesize of the progressive JPG
                    $prog_size = ewww_image_optimizer_filesize($progfile);
                    ewwwio_debug_message("progressive JPG filesize: {$prog_size}");
                    // if the progressive file is bigger
                    if ($prog_size > $non_size) {
                        // store the size of the non-progessive JPG
                        $opt_jpg_size = $non_size;
                        if (is_file($progfile)) {
                            // delete the progressive file
                            unlink($progfile);
                        }
                        ewwwio_debug_message('keeping non-progressive JPG');
                        // if the progressive file is smaller or the same
                    } else {
                        // store the size of the progressive JPG
                        $opt_jpg_size = $prog_size;
                        // replace the non-progressive with the progressive file
                        rename($progfile, $tempfile);
                        ewwwio_debug_message('keeping progressive JPG');
                    }
                    // if the best-optimized is smaller than the original JPG, and we didn't create an empty JPG
                    if ($jpg_size > $opt_jpg_size && $opt_jpg_size != 0) {
                        // replace the original with the optimized file
                        rename($tempfile, $jpgfile);
                        // store the size of the optimized JPG
                        $jpg_size = $opt_jpg_size;
                        ewwwio_debug_message('optimized JPG was smaller than un-optimized version');
                        // if the optimization didn't produce a smaller JPG
                    } elseif (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                }
                ewwwio_debug_message("converted JPG size: {$jpg_size}");
                // if the new JPG is smaller than the original PNG
                if ($new_size > $jpg_size && $jpg_size != 0 && ewww_image_optimizer_mimetype($jpgfile, 'i') == 'image/jpeg') {
                    // store the size of the JPG as the new filesize
                    $new_size = $jpg_size;
                    // if the user wants originals delted after a conversion
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original PNG
                        unlink($file);
                    }
                    // update the $file location to the new JPG
                    $file = $jpgfile;
                    // let webp know what we're dealing with now
                    $type = 'image/jpeg';
                    // successful conversion, so we store the increment
                    $converted = $filenum;
                } else {
                    $converted = FALSE;
                    if (is_file($jpgfile)) {
                        // otherwise delete the new JPG
                        unlink($jpgfile);
                    }
                }
            }
            ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
            break;
        case 'image/gif':
            // if gif2png is turned on, and the image is in the wordpress media library
            if ((ewww_image_optimizer_get_option('ewww_image_optimizer_gif_to_png') || !empty($_GET['ewww_convert'])) && $gallery_type == 1 && !ewww_image_optimizer_is_animated($file)) {
                // generate the filename for a PNG
                // if this is a resize version
                if ($converted) {
                    // just change the file extension
                    $pngfile = preg_replace('/\\.\\w+$/', '.png', $file);
                    // if this is the full version
                } else {
                    // construct the filename for the new PNG
                    list($pngfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.png');
                }
            } else {
                // turn conversion OFF
                $convert = false;
                $pngfile = '';
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_cloud_key') && ewww_image_optimizer_get_option('ewww_image_optimizer_gif_level') == 10) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $pngfile, 'image/png', $skip_lossy);
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/png', null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(false, !$skip['optipng'], !$skip['gifsicle'], !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(false, false, !$skip['gifsicle'], false, false, false);
            }
            // if gifsicle is disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_gif_level') == 0) {
                // return an appropriate message
                $result = __('GIF optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // if utility checking is on, and gifsicle is not installed
            } elseif (!$skip['gifsicle'] && !$tools['GIFSICLE']) {
                // return an appropriate message
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>gifsicle</em>');
            } else {
                // otherwise, turn optimization ON
                $optimize = true;
            }
            // if optimization is turned ON
            if ($optimize) {
                $tempfile = $file . '.tmp';
                //temporary GIF output
                // run gifsicle on the GIF
                exec("{$nice} " . $tools['GIFSICLE'] . " -O3 --careful -o {$tempfile} " . ewww_image_optimizer_escapeshellarg($file));
                // retrieve the filesize of the temporary GIF
                $new_size = ewww_image_optimizer_filesize($tempfile);
                // if the new GIF is smaller
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller GIF
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both turned OFF, we are done here
            } elseif (!$convert) {
                break;
            }
            // get the new filesize for the GIF
            $new_size = ewww_image_optimizer_filesize($file);
            // if conversion is ON and the GIF isn't animated
            if ($convert && !ewww_image_optimizer_is_animated($file)) {
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                // if optipng is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng') && $tools['OPTIPNG']) {
                    // retrieve the optipng optimization level
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // run optipng on the GIF file
                    exec("{$nice} " . $tools['OPTIPNG'] . " -out " . ewww_image_optimizer_escapeshellarg($pngfile) . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($file));
                }
                // if pngout is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout') && $tools['PNGOUT']) {
                    // retrieve the pngout optimization level
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // if $pngfile exists (which means optipng was run already)
                    if (file_exists($pngfile)) {
                        // run pngout on the PNG file
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($pngfile));
                    } else {
                        // run pngout on the GIF file
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($file) . " " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                // retrieve the filesize of the PNG
                $png_size = ewww_image_optimizer_filesize($pngfile);
                // if the new PNG is smaller than the original GIF
                if ($new_size > $png_size && $png_size != 0 && ewww_image_optimizer_mimetype($pngfile, 'i') == 'image/png') {
                    // store the PNG size as the new filesize
                    $new_size = $png_size;
                    // if the user wants original GIFs deleted after successful conversion
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original GIF
                        unlink($file);
                    }
                    // update the $file location with the new PNG
                    $file = $pngfile;
                    // let webp know what we're dealing with now
                    $type = 'image/png';
                    // normally this would be at the end of the section, but we only want to do webp if the image was successfully converted to a png
                    ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
                    // successful conversion (for now), so we store the increment
                    $converted = $filenum;
                } else {
                    $converted = FALSE;
                    if (is_file($pngfile)) {
                        unlink($pngfile);
                    }
                }
            }
            break;
        case 'application/pdf':
            if (empty($_REQUEST['ewww_force'])) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, false, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_pdf_level') > 0) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type);
            }
            break;
        default:
            // if not a JPG, PNG, or GIF, tell the user we don't work with strangers
            return array($file, __('Unknown type: ' . $type, EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
    }
    // allow other plugins to run operations on the images after optimization.
    // NOTE: it is recommended to do any image modifications prior to optimization, otherwise you risk un-optimizing your images here.
    do_action('ewww_image_optimizer_post_optimization', $file, $type);
    // if their cloud api license limit has been exceeded
    if ($result == 'exceeded') {
        return array($file, __('License exceeded', EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
    }
    if (!empty($new_size)) {
        // Set correct file permissions
        $stat = stat(dirname($file));
        $perms = $stat['mode'] & 0666;
        //same permissions as parent folder, strip off the executable bits
        @chmod($file, $perms);
        $results_msg = ewww_image_optimizer_update_table($file, $new_size, $orig_size, $new);
        ewwwio_memory(__FUNCTION__);
        return array($file, $results_msg, $converted, $original);
    }
    ewwwio_memory(__FUNCTION__);
    // otherwise, send back the filename, the results (some sort of error message), the $converted flag, and the name of the original image
    return array($file, $result, $converted, $original);
}
Exemple #22
0
    function createFavicon()
    {
        $favicon_image = $this->_params->get('favicon_image');
        $favicon_path = 'templates/blank_j3/favicon/';
        if (isset($favicon_image)) {
            if (!is_dir(__DIR__ . '/../favicon')) {
                mkdir(__DIR__ . '/../favicon', 0777, true);
            }
            $favicon_set = array('apple-touch-icon' => array(57, 60, 72, 76, 114, 120, 144, 152), 'favicon' => array(16, 32, 96, 160, 196), 'mstile' => array(70, 144, 150, 310));
            $return_favicons = '';
            // create favicons for all except Win
            foreach ($favicon_set as $name => $sizes) {
                foreach ($sizes as $size) {
                    $favicon_name = "{$name}-{$size}" . "x{$size}.png";
                    $outFile = __DIR__ . "/../favicon/{$favicon_name}";
                    $image = new Imagick($favicon_image);
                    $image->adaptiveResizeImage($size, $size, true);
                    $image->setImageBackgroundColor('None');
                    $image->thumbnailImage($size, $size, 1, 'None');
                    $image->writeImage($outFile);
                    //echo "<img src='$favicon_path/$favicon_name' />";
                    if ($name != 'mstile') {
                        $return_favicons .= "<link rel='{$name}' sizes='{$size}" . "x{$size}' href='{$favicon_path}/{$favicon_name}'>";
                    }
                    unset($image);
                }
            }
            // create favicon for Win
            // generate XML
            $tile_bg_win = $this->_params->get('bg_win');
            $xml_data = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="{$favicon_path}/mstile-70x70.png"/>
      <square150x150logo src="{$favicon_path}/mstile-150x150.png"/>
      <square310x310logo src="{$favicon_path}/mstile-310x310.png"/>
      <wide310x150logo src="{$favicon_path}/mstile-310x150.png"/>
      <TileColor>{$tile_bg_win}</TileColor>
    </tile>
  </msapplication>
</browserconfig>
XML;
            file_put_contents(__DIR__ . "/../favicon/browserconfig.xml", $xml_data);
            $return_favicons .= "<meta name='msapplication-TileColor' content='{$tile_bg_win}'>";
            $return_favicons .= "<meta name='msapplication-TileImage' content='{$favicon_path}/mstile-144x144.png'>";
            $return_favicons .= "<meta name='msapplication-config' content='{$favicon_path}/browserconfig.xml'>";
            // generate favicon.ico
            $image = new Imagick($favicon_image);
            $image->cropThumbnailImage(32, 32);
            $image->setFormat('ico');
            $image->writeImage("{$favicon_path}/favicon.ico");
            unset($image);
            $return_favicons .= "<link rel='shortcut icon' href='{$favicon_path}/favicon.ico'>";
            return $return_favicons;
        }
    }
Exemple #23
0
 /**
  * Resize image to a given size. Use only to shrink an image.
  * If an image is smaller than specified size it will be not resized.
  *
  * @param int     $size           Max width/height size
  * @param string  $filename       Output filename
  * @param boolean $browser_compat Convert to image type displayable by any browser
  *
  * @return mixed Output type on success, False on failure
  */
 public function resize($size, $filename = null, $browser_compat = false)
 {
     $result = false;
     $rcube = rcube::get_instance();
     $convert = $rcube->config->get('im_convert_path', false);
     $props = $this->props();
     if (empty($props)) {
         return false;
     }
     if (!$filename) {
         $filename = $this->image_file;
     }
     // use Imagemagick
     if ($convert || class_exists('Imagick', false)) {
         $p['out'] = $filename;
         $p['in'] = $this->image_file;
         $type = $props['type'];
         if (!$type && ($data = $this->identify())) {
             $type = $data[0];
         }
         $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
         $p['intype'] = $type;
         // convert to an image format every browser can display
         if ($browser_compat && !in_array($type, array('jpg', 'gif', 'png'))) {
             $type = 'jpg';
         }
         // If only one dimension is greater than the limit convert doesn't
         // work as expected, we need to calculate new dimensions
         $scale = $size / max($props['width'], $props['height']);
         // if file is smaller than the limit, we do nothing
         // but copy original file to destination file
         if ($scale >= 1 && $p['intype'] == $type) {
             $result = $this->image_file == $filename || copy($this->image_file, $filename) ? '' : false;
         } else {
             $valid_types = "bmp,eps,gif,jp2,jpg,png,svg,tif";
             if (in_array($type, explode(',', $valid_types))) {
                 // Valid type?
                 if ($scale >= 1) {
                     $width = $props['width'];
                     $height = $props['height'];
                 } else {
                     $width = intval($props['width'] * $scale);
                     $height = intval($props['height'] * $scale);
                 }
                 // use ImageMagick in command line
                 if ($convert) {
                     $p += array('type' => $type, 'quality' => 75, 'size' => $width . 'x' . $height);
                     $result = rcube::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace sRGB -strip' . ' -quality {quality} -resize {size} {intype}:{in} {type}:{out}', $p);
                 } else {
                     try {
                         $image = new Imagick($this->image_file);
                         try {
                             // it throws exception on formats not supporting these features
                             $image->setImageBackgroundColor('white');
                             $image->setImageAlphaChannel(11);
                             $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
                         } catch (Exception $e) {
                             // ignore errors
                         }
                         $image->setImageColorspace(Imagick::COLORSPACE_SRGB);
                         $image->setImageCompressionQuality(75);
                         $image->setImageFormat($type);
                         $image->stripImage();
                         $image->scaleImage($width, $height);
                         if ($image->writeImage($filename)) {
                             $result = '';
                         }
                     } catch (Exception $e) {
                         rcube::raise_error($e, true, false);
                     }
                 }
             }
         }
         if ($result === '') {
             @chmod($filename, 0600);
             return $type;
         }
     }
     // do we have enough memory? (#1489937)
     if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && !$this->mem_check($props)) {
         return false;
     }
     // use GD extension
     if ($props['gd_type']) {
         if ($props['gd_type'] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) {
             $image = imagecreatefromjpeg($this->image_file);
             $type = 'jpg';
         } else {
             if ($props['gd_type'] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) {
                 $image = imagecreatefromgif($this->image_file);
                 $type = 'gif';
             } else {
                 if ($props['gd_type'] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')) {
                     $image = imagecreatefrompng($this->image_file);
                     $type = 'png';
                 } else {
                     // @TODO: print error to the log?
                     return false;
                 }
             }
         }
         if ($image === false) {
             return false;
         }
         $scale = $size / max($props['width'], $props['height']);
         // Imagemagick resize is implemented in shrinking mode (see -resize argument above)
         // we do the same here, if an image is smaller than specified size
         // we do nothing but copy original file to destination file
         if ($scale >= 1) {
             $result = $this->image_file == $filename || copy($this->image_file, $filename);
         } else {
             $width = intval($props['width'] * $scale);
             $height = intval($props['height'] * $scale);
             $new_image = imagecreatetruecolor($width, $height);
             if ($new_image === false) {
                 return false;
             }
             // Fix transparency of gif/png image
             if ($props['gd_type'] != IMAGETYPE_JPEG) {
                 imagealphablending($new_image, false);
                 imagesavealpha($new_image, true);
                 $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
                 imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
             }
             imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $props['width'], $props['height']);
             $image = $new_image;
             // fix rotation of image if EXIF data exists and specifies rotation (GD strips the EXIF data)
             if ($this->image_file && $type == 'jpg' && function_exists('exif_read_data')) {
                 $exif = exif_read_data($this->image_file);
                 if ($exif && $exif['Orientation']) {
                     switch ($exif['Orientation']) {
                         case 3:
                             $image = imagerotate($image, 180, 0);
                             break;
                         case 6:
                             $image = imagerotate($image, -90, 0);
                             break;
                         case 8:
                             $image = imagerotate($image, 90, 0);
                             break;
                     }
                 }
             }
             if ($props['gd_type'] == IMAGETYPE_JPEG) {
                 $result = imagejpeg($image, $filename, 75);
             } elseif ($props['gd_type'] == IMAGETYPE_GIF) {
                 $result = imagegif($image, $filename);
             } elseif ($props['gd_type'] == IMAGETYPE_PNG) {
                 $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
             }
         }
         if ($result) {
             @chmod($filename, 0600);
             return $type;
         }
     }
     // @TODO: print error to the log?
     return false;
 }
 public function generate_book_front_thumbnail($cover_img = '', $book_name = '', $book_author = '', $width = 196, $height = 144)
 {
     $book_template = $this->config->item('book_template');
     $im = new Imagick($book_template);
     $im->setImageBackgroundColor('white');
     $im = $im->flattenImages();
     $im->scaleImage($width, $height);
     //echo $cover_img;
     if (strlen($cover_img) > 0) {
         // Open the watermark
         $watermark = new Imagick();
         $watermark->readImage($cover_img);
         //echo "cover_img: $cover_img";
         // how big are the images?
         $iWidth = $im->getImageWidth();
         $iHeight = $im->getImageHeight();
         //let check if we need to scale the book cover image to position it in the book template properly
         $watermark_sizes = $this->scale_watermark($watermark, $iHeight, $iWidth);
         $wHeight = $watermark_sizes['height'];
         $wWidth = $watermark_sizes['width'];
         // calculate the position
         $x = $iWidth / 2 - $wWidth / 2;
         $y = $iHeight / 2 - $wHeight / 2;
         $watermark->scaleImage($wWidth, $wHeight);
         // Overlay the watermark on the original image
         $im->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
     }
     /* Create a drawing object and set the font size */
     $text_watermark = new Imagick();
     $draw = new ImagickDraw();
     /*** set the font size ***/
     // Set font properties
     //$draw->setFont('Arial');
     $draw->setFontSize(20);
     //$draw->setFillColor('black');
     //annovate with book name
     $draw->setGravity(Imagick::GRAVITY_NORTH);
     $im->annotateImage($draw, 0, 0, 0, $book_name);
     //annotate with book author
     $draw->setGravity(Imagick::GRAVITY_SOUTH);
     $im->annotateImage($draw, 0, 0, 0, $book_author);
     //$im->compositeImage($text_watermark, imagick::COMPOSITE_OVER, 0, 0);
     $im->thumbnailImage($width, $height);
     /**** set to png ***/
     $im->setImageFormat("png");
     return $im;
 }
 public function saveLogo($logoSpecs)
 {
     try {
         $logoName = md5(microtime(true) . uniqid(microtime(true)));
         $logoPath = ROOT_PATH . '/uploads/logos/' . $logoName . '/';
         mkdir($logoPath, 0777);
         chmod($logoPath, 0777);
         $image = new \Imagick($logoSpecs['tmp_name']);
         $saveLogoPath = $logoPath . $logoName . '.png';
         $image->setImageBackgroundColor('transparent');
         $image->stripimage();
         $image->setimageformat('png');
         $image->writeImage($saveLogoPath);
         $image->destroy();
         $image->clear();
         // convert to paa
         $this->convert($saveLogoPath);
         return $logoName;
     } catch (\Exception $e) {
         return false;
     }
     return false;
 }
Exemple #26
0
    private function createThumb($src, $dist, $new_w, $new_h, $resize_type, $watermark) {
        if (file_exists($dist)) {
            if (!is_writable($dist)) { return false; }
            unlink($dist);
        }
        
        if (!in_array($resize_type, array('exact', 'auto', 'crop', 'portrait', 'landscape'))) {
            $resize_type = 'auto';
        }
        
        if (!in_array($watermark, array('lt', 'lc', 'lb', 'rt', 'rc', 'rb', 'tc', 'c', 'bc')) && $watermark !== false) {
            $watermark = 'rb';
        }
        
        if ((int)$new_w) {
            if (
                ($this->w < $new_w && $this->h < $new_h) || 
                ($resize_type == 'portrait' && $this->h < $new_h) || 
                ($resize_type == 'landscape' && $this->w < $new_w)
            ) {
                copy($src, $dist);
            } else {
                $new_size = $this->getNewImageSize($new_w, $new_h, $resize_type);
                
                if ($this->Imagick === true) {
                    $image = new Imagick($src);
                    
                    switch ($resize_type) {
                        case 'auto':
                            if ($this->ext == 'gif'){
                                foreach ($image as $img) {
                                    $img->resizeImage($new_w, $new_h, Imagick::FILTER_LANCZOS, 1, true);
                                    $img->setImagePage($img->getImageWidth(), $img->getImageHeight(), 0, 0);
                                }
                            } else {
                                $image->resizeImage($new_w, $new_h, Imagick::FILTER_LANCZOS, 1, true);
                            }
                            
                            break;
                        case 'portrait':
                            if ($this->ext == 'gif'){
                                foreach ($image as $img) {
                                    $img->resizeImage(0, $new_h, Imagick::FILTER_LANCZOS, 1);
                                    $img->setImagePage($img->getImageWidth(), $img->getImageHeight(), 0, 0);
                                }
                            } else {
                                $image->resizeImage(0, $new_h, Imagick::FILTER_LANCZOS, 1);
                            }
                            break;
                        case 'landscape':
                            if ($this->ext == 'gif'){
                                foreach ($image as $img) {
                                    $img->resizeImage($new_w, 0, Imagick::FILTER_LANCZOS, 1);
                                    $img->setImagePage($img->getImageWidth(), $img->getImageHeight(), 0, 0);
                                }
                            } else {
                                $image->resizeImage($new_w, 0, Imagick::FILTER_LANCZOS, 1);
                            }
                            break;
                        case 'exact':
                            if ($this->ext == 'gif'){
                                foreach ($image as $img) {
                                    $img->resizeImage($new_w, $new_h, Imagick::FILTER_LANCZOS, 1);
                                    $img->setImagePage($img->getImageWidth(), $img->getImageHeight(), 0, 0);
                                }
                            } else {
                                $image->resizeImage($new_w, $new_h, Imagick::FILTER_LANCZOS, 1);
                            }
                            break;
                        case 'crop':
                            if ($this->ext == 'gif') {
                                foreach ($image as $img) {
                                    $img->cropThumbnailImage($new_w, $new_h);
                                    $img->setImagePage($img->getImageWidth(), $img->getImageHeight(), 0, 0);
                                }
                            } else {
                                $image->cropThumbnailImage($new_w, $new_h);
                            }
                            break;
                    }
                    
                    $image->setImageCompressionQuality($this->quality);
                    
                    if ($this->ext == 'jpg') {
                        $image->setImageBackgroundColor('white');
                        $image->flattenImages();
                        $image = $image->flattenImages();
                        $image->setImageCompression(Imagick::COMPRESSION_JPEG);
                    }
                    
                    $image->setImageFormat($this->ext);
                    
                    if ($this->ext == 'gif') {
                        $image->writeimages($dist);
                    } else {
                        $image->writeimage($dist);
                    }

                    $image->destroy();
                } else {
                    $this->new_img = imagecreatetruecolor($new_size['w'], $new_size['h']);

                    imagecopyresampled($this->new_img, $this->old_img, 0, 0, 0, 0, $new_size['w'], $new_size['h'], $this->w, $this->h);

                    if ($resize_type == 'crop') {
                        $this->crop($new_size['w'], $new_size['h'], $new_w, $new_h);
                    }

                    if ($this->ext != 'gif' || $this->Imagick === true) {
                        $this->saveImage($dist, $this->ext);
                    } else {
                        $gif_resize = new gifresizer();
                        $gif_resize->resize($src, $dist, $new_w, $new_h);
                    }
                }
            }
            
            if (!empty($watermark)) {
                self::addWatermark($dist, false, $watermark);
            }
        } else if ($new_w == 'copy') {
            copy($src, $dist);
        }
    }
Exemple #27
0
 protected function _do_background($r, $g, $b, $opacity)
 {
     // Create a RGB color for the background
     $color = sprintf('rgb(%d, %d, %d)', $r, $g, $b);
     // Create a new image for the background
     $background = new Imagick();
     $background->newImage($this->width, $this->height, new ImagickPixel($color));
     if (!$background->getImageAlphaChannel()) {
         // Force the image to have an alpha channel
         $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
     }
     // Clear the background image
     $background->setImageBackgroundColor(new ImagickPixel('transparent'));
     // NOTE: Using setImageOpacity will destroy current alpha channels!
     $background->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity / 100, Imagick::CHANNEL_ALPHA);
     // Match the colorspace between the two images before compositing
     $background->setColorspace($this->im->getColorspace());
     if ($background->compositeImage($this->im, Imagick::COMPOSITE_DISSOLVE, 0, 0)) {
         // Replace the current image with the new image
         $this->im = $background;
         return TRUE;
     }
     return FALSE;
 }
 function renderResize()
 {
     $imagick = new \Imagick(realpath($this->control->getImagePath()));
     $points = array(400, 200);
     $imagick->setImageBackgroundColor("#fad888");
     $imagick->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_BACKGROUND);
     $imagick->distortImage(\Imagick::DISTORTION_RESIZE, $points, TRUE);
     header("Content-Type: image/jpeg");
     echo $imagick;
 }
 public function logoFileAction()
 {
     $squadID = $this->params('id', null);
     $squadReposiory = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Squad');
     /** @var Squad $squad */
     $squad = $squadReposiory->findOneBy(array('privateID' => $squadID));
     if (!$squad) {
         $response = $this->getResponse();
         $response->setStatusCode(404);
         $response->setContent('');
         return $response;
     }
     $squadImageService = $this->getServiceLocator()->get('SquadImageService');
     $squadLogoPath = $squadImageService->getServerSquadLogo($squad);
     if (!$squadLogoPath) {
         $response = $this->getResponse();
         $response->setStatusCode(404);
         $response->setContent('');
         return $response;
     }
     $response = $this->getResponse();
     if ($response instanceof Response) {
         $headers = $this->response->getHeaders();
         $headers->addHeaderLine('Content-Type', 'image/plain');
     }
     if ($squad->getSquadLogoPaa()) {
         // return paa
         header('Content-Description: File Transfer');
         header('Content-Type: application/octet-stream');
         header('Content-Disposition: attachment; filename=' . basename($squad->getSquadLogoPaa()));
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         header('Content-Length: ' . filesize(ROOT_PATH . $squad->getSquadLogoPaa()));
         ob_clean();
         flush();
         readfile(ROOT_PATH . $squad->getSquadLogoPaa());
         die;
     }
     // return normal image
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=' . basename($squad->getSquadLogo()));
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Pragma: public');
     header('Content-Length: ' . filesize(ROOT_PATH . $squad->getSquadLogo()));
     ob_clean();
     flush();
     $image = new \Imagick(ROOT_PATH . $squad->getSquadLogo());
     $image->setImageBackgroundColor('white');
     $image->setimageformat('jpg');
     echo $image;
     die;
 }
$Imagick = new \Imagick(realpath($source_image_gif));
$Imagick->rotateImage(new \ImagickPixel('rgba(255, 255, 255, 0)'), calculateCounterClockwise(270));
$save_image_link = 'imagick-crop-1920x1281-rotate-from-original-source.gif';
$save_result = $Imagick->writeImage($processed_images_fullpath . $save_image_link);
$Imagick->clear();
var_dump($save_result);
echo '<a href="' . $processed_images_folder . $save_image_link . '">rotated image</a>' . "\n";
echo '<hr>' . "\n\n";
// resize 6 (save to .png)
$Imagick = new \Imagick(realpath($source_image_gif));
$Imagick->resizeImage($new_width1, $new_height1, \Imagick::FILTER_LANCZOS, 1);
$Imagick->setImagePage(0, 0, 0, 0);
// required to resize NON animated gif
$save_image_link = 'imagick-resize-900x600-from-gif.png';
// convert transparency gif to white before save to another extension
$Imagick->setImageBackgroundColor('white');
// convert from transparent to white. for GIF source
$Imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
// convert from transparent to white. for GIF source
$Imagick = $Imagick->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
// convert from transparent to white. for GIF source
// -----------------------------------------------------------------------------------------------
$save_result = $Imagick->writeImage($processed_images_fullpath . $save_image_link);
var_dump($save_result);
echo '<a href="' . $processed_images_folder . $save_image_link . '">resized image</a>' . "\n";
$image_data = getimagesize($processed_images_folder . $save_image_link);
echo '<pre>' . print_r($image_data, true) . '</pre>';
echo '<hr>' . "\n\n";
// resize 7 (save to .jpg)
$save_image_link = 'imagick-resize-900x600-from-gif.jpg';
// convert transparency gif to white before save to another extension