Pimcore\Image\Optimizer::optimize PHP Method

optimize() public static method

public static optimize ( $path )
$path
    public static function optimize($path)
    {
        $workingPath = $path;
        if (!stream_is_local($path)) {
            $workingPath = self::getTempFile();
            copy($path, $workingPath);
        }
        $format = getimagesize($workingPath);
        if (is_array($format) && array_key_exists("mime", $format)) {
            $format = strtolower(str_replace("image/", "", $format["mime"]));
            $optimizedFiles = [];
            $supportedOptimizers = ["png" => ["pngcrush", "zopflipng", "pngout", "advpng"], "jpeg" => ["jpegoptim", "cjpeg"]];
            if (isset($supportedOptimizers[$format])) {
                foreach ($supportedOptimizers[$format] as $optimizer) {
                    $optimizerMethod = "optimize" . $optimizer;
                    $optimizedFile = self::$optimizerMethod($workingPath);
                    if ($optimizedFile && file_exists($optimizedFile)) {
                        $optimizedFiles[] = ["filesize" => filesize($optimizedFile), "path" => $optimizedFile, "optimizer" => $optimizer];
                    }
                }
                // order by filesize
                usort($optimizedFiles, function ($a, $b) {
                    if ($a["filesize"] == $b["filesize"]) {
                        return 0;
                    }
                    return $a["filesize"] < $b["filesize"] ? -1 : 1;
                });
                // first entry is the smallest -> use this one
                if (count($optimizedFiles)) {
                    copy($optimizedFiles[0]["path"], $path);
                }
                // cleanup
                foreach ($optimizedFiles as $tmpFile) {
                    unlink($tmpFile["path"]);
                }
                if (!stream_is_local($path)) {
                    unlink($workingPath);
                }
            }
        }
    }

Usage Example

コード例 #1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $files = rscandir(PIMCORE_TEMPORARY_DIRECTORY . "/image-thumbnails/");
     $savedBytesTotal = 0;
     foreach ($files as $file) {
         if (file_exists($file)) {
             $originalFilesize = filesize($file);
             \Pimcore\Image\Optimizer::optimize($file);
             $savedBytes = $originalFilesize - filesize($file);
             $savedBytesTotal += $savedBytes;
             $this->output->writeln("Optimized image: " . $file . " saved " . formatBytes($savedBytes));
         }
     }
     $this->output->writeln("Finished!");
     $this->output->writeln("Saved " . formatBytes($savedBytesTotal) . " in total");
 }
All Usage Examples Of Pimcore\Image\Optimizer::optimize