/** * Info about driver's version * * @param string $sDriver * * @return bool */ public function GetDriverVersion($sDriver) { $sVersion = false; $sDriver = strtolower($sDriver); if (isset($this->aDrivers[$sDriver])) { if ($this->aDrivers[$sDriver] == 'Imagick') { if (class_exists('Imagick')) { $img = new \Imagick(); $aInfo = $img->getVersion(); $sVersion = $aInfo['versionString']; if (preg_match('/\\w+\\s\\d+\\.[\\d\\.\\-]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } elseif ($this->aDrivers[$sDriver] == 'Gmagick') { if (class_exists('Gmagick')) { $img = new \Gmagick(); $aInfo = $img->getVersion(); $sVersion = $aInfo['versionString']; if (preg_match('/\\w+\\s\\d+\\.[\\d\\.\\-]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } else { if (function_exists('gd_info')) { $aInfo = gd_info(); $sVersion = $aInfo['GD Version']; if (preg_match('/\\d+\\.[\\d\\.]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } } return $sVersion; }
/** * Get version. * * @return string */ public function getVersion() { if (null === self::$version) { $gmagick = new \Gmagick(); $version = $gmagick->getVersion(); list(self::$version) = sscanf($version['versionString'], 'GraphicsMagick %s %04d-%02d-%02d %s %s'); } return self::$version; }
/** * (non-PHPdoc) * @see Imagine\Image\FontInterface::box() */ public function box($string, $angle = 0) { $text = new \GmagickDraw(); $text->setfont($this->file); $text->setfontsize($this->size); $text->setfontstyle(\Gmagick::STYLE_OBLIQUE); $info = $this->gmagick->queryfontmetrics($text, $string); $box = new Box($info['textWidth'], $info['textHeight']); return $box; }
function setcontentsource($source, $x, $y, $width, $height, $bestfit = true) { $myimage = new Gmagick(); $myimage->readimageblob($source); $myimage->thumbnailImage($width, $height, $bestfit); $this->im->compositeImage($myimage, gmagick::COMPOSITE_OVER, $x, $y); //图片与画布合成 $myimage->clear(); $myimage->destroy(); //释放资源 }
function out() { if (self::DEBUG) { echo __FUNCTION__ . "\n"; } $image = new \Gmagick(); $image->newimage($this->width, $this->height); $image->drawimage($this->canvas); $tmp = tempnam("", "gm"); $image->write($tmp); return file_get_contents($tmp); }
public function process($args) { $frame_path = Kohana::config('recipe.compositeframe'); if (!isset($frame_path) or !file_exists($frame_path)) { return; } $frame = new Gmagick(); $frame->readImage($frame_path); $w = $frame->getimagewidth(); $h = $frame->getimageheight(); $this->crop($w, $h); $this->image->compositeImage($frame, Gmagick::COMPOSITE_OVER, 0, 0); // Some comp styles seem to throw errors! }
/** * {@inheritdoc} */ public function box($string, $angle = 0) { $text = new \GmagickDraw(); $text->setfont($this->file); /** * @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027 * * ensure font resolution is the same as GD's hard-coded 96 */ $text->setfontsize((int) ($this->size * (96 / 72))); $text->setfontstyle(\Gmagick::STYLE_OBLIQUE); $info = $this->gmagick->queryfontmetrics($text, $string); $box = new Box($info['textWidth'], $info['textHeight']); return $box; }
/** * {@inheritdoc} */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0) { try { $pixel = $this->getColor($font->getColor()); $text = new \GmagickDraw(); $text->setfont($font->getFile()); /** * @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027 * * ensure font resolution is the same as GD's hard-coded 96 */ $text->setfontsize((int) ($font->getSize() * (96 / 72))); $text->setfillcolor($pixel); $info = $this->gmagick->queryfontmetrics($text, $string); $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); $x1 = round(0 * $cos - 0 * $sin); $x2 = round($info['textWidth'] * $cos - $info['textHeight'] * $sin); $y1 = round(0 * $sin + 0 * $cos); $y2 = round($info['textWidth'] * $sin + $info['textHeight'] * $cos); $xdiff = 0 - min($x1, $x2); $ydiff = 0 - min($y1, $y2); $this->gmagick->annotateimage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string); $pixel = null; $text = null; } catch (\GmagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } return $this; }
/** * (non-PHPdoc) * @see Imagine\Draw\DrawerInterface::text() */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0) { try { $pixel = $this->getColor($font->getColor()); $text = new \GmagickDraw(); $text->setfont($font->getFile()); $text->setfontsize($font->getSize()); $text->setfillcolor($pixel); $info = $this->gmagick->queryfontmetrics($text, $string); $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); $x1 = round(0 * $cos - 0 * $sin); $x2 = round($info['textWidth'] * $cos - $info['textHeight'] * $sin); $y1 = round(0 * $sin + 0 * $cos); $y2 = round($info['textWidth'] * $sin + $info['textHeight'] * $cos); $xdiff = 0 - min($x1, $x2); $ydiff = 0 - min($y1, $y2); $this->gmagick->annotateimage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string); $pixel = null; $text = null; } catch (\GmagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } }
function generate_thumbnail($originName, $thumbnailName, $path, $width = 255, $height = 255) { // use third part toolkit to process photos // TODO // Instantiate a new Gmagick object $image = new Gmagick('/var/www/html/ant/uploads/mv.jpg'); // Make thumbnail from image loaded. 0 for either axes preserves aspect ratio //$image->thumbnailImage(150, 0); $image->thumbnailImage($width, $height); // Create a border around the image, then simulate how the image will look like as an oil painting // Notice the chaining of mutator methods which is supported in gmagick // $image->borderImage("yellow", 8, 8)->oilPaintImage(0.3); // Write the current image at the current state to a file // $image->write('/var/www/html/ant/uploads/example_thumbnail.jpg'); $image->write('example_thumbnail.jpg'); }
/** * (non-PHPdoc) * @see Imagine\ImageInterface::histogram() */ public function histogram() { $pixels = $this->gmagick->getimagehistogram(); return array_map(function (\GmagickPixel $pixel) { $info = $pixel->getColor(); return new Color(array($info['r'], $info['g'], $info['b']), (int) round($info['a'] * 100)); }, $pixels); }
/** * Sets colorspace and image type, assigns the palette. * * @param PaletteInterface $palette * * @throws InvalidArgumentException */ private function setColorspace(PaletteInterface $palette) { if (!isset(static::$colorspaceMapping[$palette->name()])) { throw new InvalidArgumentException(sprintf('The palette %s is not supported by Gmagick driver', $palette->name())); } $this->gmagick->setimagecolorspace(static::$colorspaceMapping[$palette->name()]); $this->palette = $palette; }
/** * {@inheritdoc} */ public function count() { try { return $this->resource->getnumberimages(); } catch (\GmagickException $e) { throw new RuntimeException('Failed to count the number of layers', $e->getCode(), $e); } }
/** * {@inheritdoc} */ public function scale(BoxInterface $size) { try { $this->gmagick->scaleimage($size->getWidth(), $size->getHeight()); } catch (\GmagickException $e) { throw new RuntimeException('Scale operation failed', $e->getCode(), $e); } return $this; }
/** * {@inheritdoc} */ public function getColorProfile() { try { $data = $this->gmagick->getimageprofile('ICM'); } catch (\GmagickException $exception) { return null; } return new ColorProfile(StreamUtils::create($data)); }
/** * Checks to see if editor supports the mime-type specified. * * @since 3.5.0 * @access public * * @param string $mime_type * @return boolean */ public static function supports_mime_type($mime_type) { $gmagick_extension = strtoupper(self::get_extension($mime_type)); if (!$gmagick_extension) { return false; } // setimageindex is optional unless mime is an animated format. // Here, we just say no if you are missing it and aren't loading a jpeg. if (!method_exists('Gmagick', 'setimageindex') && $mime_type != 'image/jpeg') { return false; } try { $gmagick = new Gmagick(); return (bool) $gmagick->queryformats($gmagick_extension); } catch (Exception $e) { return false; } }
protected function load($size = null) { try { $magick = new \Gmagick(); if ($this->format === IMG_JPG && $size !== null) { $magick->setsize($size[0], $size[1]); } $magick->readimage($this->filename); } catch (\Exception $e) { throw new \Imagine\Exception\RuntimeException("Gmagick: Unable to open image {$this->filename}. {$e->getMessage()}", $e->getCode(), $e); } if ($this->format === IMG_JPG && $size !== null) { $newWidth = $magick->getimagewidth(); if ($newWidth !== $this->size[0]) { $this->size = $this->prescalesize = array($newWidth, $magick->getimageheight()); } } $cs = $magick->getimagecolorspace(); $this->image = new Image($magick, RImagine::createPalette($cs), $this->metadata); if ($cs === \Gmagick::COLORSPACE_CMYK) { // convert CMYK > RGB try { $this->image->usePalette(new RGB()); } catch (\Exception $e) { $this->image->getGmagick()->stripimage(); // make sure all profiles are removed } } }
/** * Internal * * Flatten the image. */ private function flatten() { /** * @see http://pecl.php.net/bugs/bug.php?id=22435 */ if (method_exists($this->gmagick, 'flattenImages')) { try { $this->gmagick = $this->gmagick->flattenImages(); } catch (\GmagickException $e) { throw new RuntimeException('Flatten operation failed', $e->getCode(), $e); } } }
public function process($args) { if (isset($args[0])) { $rotation = $args[0]; } else { $rotation = mt_rand(-5, 5); } if (isset($args[1])) { $signature = $args[1]; } /* -------------------------- */ $frame_path = DOCROOT . "/staticfiles/img/polaroids/blog_polaroid_frame.png"; if (!isset($frame_path) or !file_exists($frame_path)) { return; } // Load the frame and crop the requested image $frame = new Gmagick(); $frame->readImage($frame_path); $w = $frame->getimagewidth(); $h = $frame->getimageheight(); $this->crop(85, 90); $x = 10; $y = 15; $this->image->borderImage("transparent", $x, $y); // Have to add a border as the x displacement in compositeImage() is broken! $this->image->compositeImage($frame, Gmagick::COMPOSITE_OVER, 0, 0); // Some comp styles seem to throw errors! // Add the signature if we have been asked for one if (isset($signature)) { $sig_path = DOCROOT . "/staticfiles/img/polaroids/" . $signature . "_sig.png"; if (!file_exists($sig_path)) { return; } $sig = new Gmagick(); $sig->readImage($sig_path); $sw = $sig->getimagewidth(); $sh = $sig->getimageheight(); $x = ($this->image->getimagewidth() - $sig->getimagewidth()) / 2; $y = 330; // Have to add a border as the x displacement in compositeImage() is broken! $sig->borderImage("transparent", $x, $y); $this->image->compositeImage($sig, Gmagick::COMPOSITE_OVER, 0, 0); // Some comp styles seem to throw errors! } // Rotate the image if ($rotation != 0) { $frame->magnifyimage(); $frame->magnifyimage(); $this->image->rotateimage('transparent', $rotation); $frame->minifyimage(); $frame->minifyimage(); } }
/** * {@inheritdoc} */ public function offsetUnset($offset) { try { $this->extractAt($offset); } catch (RuntimeException $e) { return; } try { $this->resource->setimageindex($offset); $this->resource->removeimage(); } catch (\GmagickException $e) { throw new RuntimeException('Unable to remove layer', $e->getCode(), $e); } }
/** * {@inheritdoc} */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0, $width = null) { try { $pixel = $this->getColor($font->getColor()); $text = new \GmagickDraw(); $text->setfont($font->getFile()); /** * @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027 * * ensure font resolution is the same as GD's hard-coded 96 */ $text->setfontsize((int) ($font->getSize() * (96 / 72))); $text->setfillcolor($pixel); $info = $this->gmagick->queryfontmetrics($text, $string); // $rad = deg2rad($angle); // $cos = cos($rad); // $sin = sin($rad); // $x1 = round(0 * $cos - 0 * $sin); // $x2 = round($info['textWidth'] * $cos - $info['textHeight'] * $sin); // $y1 = round(0 * $sin + 0 * $cos); // $y2 = round($info['textWidth'] * $sin + $info['textHeight'] * $cos); // $xdiff = 0 - min($x1, $x2); // $ydiff = 0 - min($y1, $y2); if ($width !== null) { throw new NotSupportedException('Gmagick doesn\'t support queryfontmetrics function for multiline text', 1); } // $this->gmagick->annotateimage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string); $deltaX = $info['characterWidth'] * sin(deg2rad($angle)); $deltaY = $info['characterHeight']; $posX = $position->getX() - $deltaX; if ($posX < 0) { $posX = 0; } $this->gmagick->annotateimage($text, $posX, $position->getY() + $deltaY, $angle, $string); unset($pixel, $text); } catch (\GmagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } return $this; }
private function doLoad($content, MetadataBag $metadata) { try { $gmagick = new \Gmagick(); $gmagick->readimageblob($content); } catch (\GmagickException $e) { throw new RuntimeException('Could not load image from string', $e->getCode(), $e); } return new Image($gmagick, $this->createPalette($gmagick), $metadata); }
private function drawRectangleAndReplaceExistImg($image, $height, $width) { // прямоугольник рисуем снизу изображения высотой 8% от высоты изображения $heightRectagle = $height * 0.08; $gmagicDraw = new GmagickDraw(); $gmagicDraw->setfillcolor("#fff"); $gmagicDraw->rectangle(0, $height - $heightRectagle, $width, $height); $gImage = new Gmagick(); $gImage->readImage($image); $gImage->drawimage($gmagicDraw); $gImage->writeimage($image); $gImage->destroy(); }
function thumbnail($upfiledir, $src, $tName, $tw = '', $th = '', $scale = true, $tDir = "thumb") { global $iCMS; $R = array(); $tw = empty($tw) ? $iCMS->config['thumbwidth'] : (int) $tw; $th = empty($th) ? $iCMS->config['thumbhight'] : (int) $th; if ($tw && $th) { list($width, $height, $type) = @getimagesize($src); if ($width < 1 && $height < 1) { $R['width'] = $tw; $R['height'] = $th; $R['src'] = $src; return $R; } if ($width > $tw || $height > $th) { $R['src'] = $upfiledir . $tDir . "/" . $tName . '_' . $tw . 'x' . $th . '.' . substr(strrchr($src, "."), 1); if (in_array('Gmagick', get_declared_classes())) { $image = new Gmagick(); $image->readImage($src); $im = self::scale(array("tw" => $tw, "th" => $th, "w" => $image->getImageWidth(), "h" => $image->getImageHeight())); $image->resizeImage($im['w'], $im['h'], null, 1); $image->cropImage($tw, $th, 0, 0); //$image->thumbnailImage($gm_w,$gm_h); FS::mkdir($upfiledir . $tDir); $image->writeImage($R['src']); $image->destroy(); } else { $im = self::scale(array("tw" => $tw, "th" => $th, "w" => $width, "h" => $height), $scale); $R['width'] = $im['w']; $R['height'] = $im['h']; $res = self::imagecreate($type, $src); if ($res) { $thumb = imagecreatetruecolor($im['w'], $im['h']); imagecopyresampled($thumb, $res, 0, 0, 0, 0, $im['w'], $im['h'], $width, $height); //PHP_VERSION != '4.3.2' && self::UnsharpMask($thumb); FS::mkdir($upfiledir . $tDir); self::image($thumb, $type, $R['src']); } else { $R['src'] = $src; } } } else { $R['width'] = $width; $R['height'] = $height; $R['src'] = $src; } return $R; } }
function ewww_image_optimizer_gmagick_support() { ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>'); if (extension_loaded('gmagick')) { $gmagick = new Gmagick(); $formats = $gmagick->queryFormats(); if (in_array('PNG', $formats) && in_array('JPG', $formats)) { return true; } } return false; }
public function testImageResolutionChange() { $imagine = $this->getImagine(); $image = $imagine->open('tests/Imagine/Fixtures/resize/210-design-19933.jpg'); $outfile = 'tests/Imagine/Fixtures/resize/reduced.jpg'; $image->save($outfile, array('resolution-units' => ImageInterface::RESOLUTION_PIXELSPERINCH, 'resolution-x' => 144, 'resolution-y' => 144)); if ($imagine instanceof \Imagine\Imagick\Imagine) { $i = new \Imagick($outfile); $info = $i->identifyimage(); $this->assertEquals(144, $info['resolution']['x']); $this->assertEquals(144, $info['resolution']['y']); } if ($imagine instanceof \Imagine\Gmagick\Imagine) { $i = new \Gmagick($outfile); $info = $i->getimageresolution(); $this->assertEquals(144, $info['x']); $this->assertEquals(144, $info['y']); } unlink($outfile); }
/** * 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); }
protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte) { // generate images $img = imagecreatefrompng($file); if ($img === false) { return; } // FIXME The pixel transformation doesn't work well with 8bit PNGs $eight_bit = ($byte & 4) !== 4; $wpx = imagesx($img); $hpx = imagesy($img); imagesavealpha($img, false); // create temp alpha file $tempfile_alpha = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_alpha); $tempfile_alpha = "{$tempfile_alpha}.png"; // create temp plain file $tempfile_plain = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_plain); $tempfile_plain = "{$tempfile_plain}.png"; $imgalpha = imagecreate($wpx, $hpx); imagesavealpha($imgalpha, false); // generate gray scale palette (0 -> 255) for ($c = 0; $c < 256; ++$c) { imagecolorallocate($imgalpha, $c, $c, $c); } // Use PECL gmagick + Graphics Magic to process transparent PNG images if (extension_loaded("gmagick")) { $gmagick = new Gmagick($file); $gmagick->setimageformat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel_neg = clone $gmagick; $alpha_channel_neg->separateimagechannel(Gmagick::CHANNEL_OPACITY); // Negate opacity channel $alpha_channel = new Gmagick(); $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png"); $alpha_channel->compositeimage($alpha_channel_neg, Gmagick::COMPOSITE_DIFFERENCE, 0, 0); $alpha_channel->separateimagechannel(Gmagick::CHANNEL_RED); $alpha_channel->writeimage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); // Make opaque image $color_channels = new Gmagick(); $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeimage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } elseif (extension_loaded("imagick")) { $imagick = new Imagick($file); $imagick->setFormat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel = clone $imagick; $alpha_channel->separateImageChannel(Imagick::CHANNEL_ALPHA); $alpha_channel->negateImage(true); $alpha_channel->writeImage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); // Make opaque image $color_channels = new Imagick(); $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeImage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } else { // allocated colors cache $allocated_colors = array(); // extract alpha channel for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $col = imagecolorsforindex($img, $color); $alpha = $col['alpha']; if ($eight_bit) { // with gamma correction $gammacorr = 2.2; $pixel = pow((127 - $alpha) * 255 / 127 / 255, $gammacorr) * 255; } else { // without gamma correction $pixel = (127 - $alpha) * 2; $key = $col['red'] . $col['green'] . $col['blue']; if (!isset($allocated_colors[$key])) { $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']); $allocated_colors[$key] = $pixel_img; } else { $pixel_img = $allocated_colors[$key]; } imagesetpixel($img, $xpx, $ypx, $pixel_img); } imagesetpixel($imgalpha, $xpx, $ypx, $pixel); } } // extract image without alpha channel $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($img); imagepng($imgalpha, $tempfile_alpha); imagepng($imgplain, $tempfile_plain); } // embed mask image $this->addImagePng($tempfile_alpha, $x, $y, $w, $h, $imgalpha, true); imagedestroy($imgalpha); // embed image, masked with previously embedded mask $this->addImagePng($tempfile_plain, $x, $y, $w, $h, $imgplain, false, true); imagedestroy($imgplain); // remove temp files unlink($tempfile_alpha); unlink($tempfile_plain); }
/** * @final * @global array $motopressCESettings * @global MPCERequirements $motopressCERequirements * @global stdClass $motopressCELang * @param string $icon * @param string $iconDir */ protected final function icon($icon, $iconDir) { global $motopressCESettings; global $motopressCERequirements; global $motopressCELang; if (is_string($icon)) { $icon = trim($icon); if (!empty($icon)) { $icon = filter_var($icon, FILTER_SANITIZE_STRING); if (dirname($icon) === '.') { $iconPath = $motopressCESettings['plugin_root'] . '/' . $motopressCESettings['plugin_name'] . '/images/ce/' . $iconDir . '/' . $icon; $iconUrl = $motopressCESettings['plugin_root_url'] . '/' . $motopressCESettings['plugin_name'] . '/images/ce/' . $iconDir . '/' . $icon; } else { $iconPath = WP_CONTENT_DIR . '/' . $icon; $iconUrl = WP_CONTENT_URL . '/' . $icon; } $iconUrl .= '?ver=' . $motopressCESettings['plugin_version']; if (file_exists($iconPath)) { $mimeType = null; if ($motopressCERequirements->getGd()) { $info = getimagesize($iconPath); if ($info) { $mimeType = $info['mime']; } } if (is_null($mimeType) && $motopressCERequirements->getFileinfo() && version_compare(PHP_VERSION, '5.3.0', '>=')) { $finfo = new finfo(FILEINFO_MIME_TYPE); $finfoMimeType = $finfo->file($iconPath); if ($finfoMimeType) { $mimeType = $finfoMimeType; } } if (is_null($mimeType) && $motopressCERequirements->getExif()) { $exifImageType = exif_imagetype($iconPath); if ($exifImageType) { $mimeType = image_type_to_mime_type($exifImageType); } } $extension = null; if (is_null($mimeType) && $motopressCERequirements->getImagick()) { try { $imagick = new Imagick($iconPath); $extension = strtolower($imagick->getImageFormat()); } catch (ImagickException $e) { if ($motopressCESettings['debug']) { var_dump($e); } } } if (is_null($extension) && $motopressCERequirements->getGmagick()) { try { $gmagick = new Gmagick($iconPath); $extension = strtolower($gmagick->getimageformat()); } catch (GmagickException $e) { if ($motopressCESettings['debug']) { var_dump($e); } } } if (is_null($extension)) { $extension = pathinfo($iconPath, PATHINFO_EXTENSION); } if (!is_null($mimeType) || !is_null($extension)) { if (in_array($mimeType, self::$mimeTypes) || in_array($extension, self::$extensions)) { $this->icon = $iconUrl; } else { $this->addError('icon', strtr($motopressCELang->CEIconValidation, array('%name%' => $mimeType))); } } else { $this->addError('icon', $motopressCELang->CEUnknownMimeType); } } else { $this->addError('icon', strtr($motopressCELang->fileNotExists, array('%name%' => $iconPath))); } } else { $this->addError('icon', $motopressCELang->CEEmpty); } } else { $this->addError('icon', strtr($motopressCELang->CEInvalidArgumentType, array('%name%' => gettype($icon)))); } }
<?php //Instantiate a new Gmagick object $image = new Gmagick('example.jpg'); //Make thumbnail from image loaded. 0 for either axes preserves aspect ratio $image->thumbnailImage(100, 0); //Create a border around the image, then simulate how the image will look like as an oil painting //Notice the chaining of mutator methods which is supported in gmagick $image->borderImage("yellow", 8, 8)->oilPaintImage(0.3); //Write the current image at the current state to a file $image->write('example_thumbnail.jpg');