Compress and save $image

@param string  $filePath
@param Imagick $image
@param int     $compression_quality

@return Imagick
326193
protected function saveImage($filePath, Imagick $image, $compression_quality)
    {
        $image->setImageCompression(Imagick::COMPRESSION_JPEG);
        $image->setImageCompressionQuality($compression_quality);
        $image->stripImage();
        $image->writeImage($filePath);

        return $image;
    }
192305
public function save( $filename, $mimetype )
	{
		switch( $mimetype )
		{
			case 'image/gif':

				if( @imagegif( $this->_image, $filename ) === false ) {
					throw new MW_Media_Exception( sprintf( 'Unable to save image to file "%1$s"', $filename ) );
				}

				break;

			case 'image/jpeg':

				$quality = 75;
				if( isset( $this->_options['image']['jpeg']['quality'] ) ) {
					$quality = (int) $this->_options['image']['jpeg']['quality'];
				}

				if( @imagejpeg( $this->_image, $filename, $quality ) === false ) {
					throw new MW_Media_Exception( sprintf( 'Unable to save image to file "%1$s"', $filename ) );
				}

				break;

			case 'image/png':

				$quality = 9;
				if( isset( $this->_options['image']['png']['quality'] ) ) {
					$quality = (int) $this->_options['image']['png']['quality'];
				}

				if( @imagepng( $this->_image, $filename, $quality ) === false ) {
					throw new MW_Media_Exception( sprintf( 'Unable to save image to file "%1$s"', $filename ) );
				}

				break;

			default:
				throw new MW_Media_Exception( sprintf( 'File format "%1$s" is not supported', $this->getMimeType() ) );
		}
	}
1065232
public function save($file, $quality = null)
  {
    $this->apply();

    return $this->makeImage($file, $quality);
  }
1109946
public function create($mixed, $savePath, $width, $height, $fit = false, $format = false)
    {
        if ($format === false) {
            $format = $this->getThumbnailsFormat();
        }
        switch ($format) {
            case ThumbnailFormatService::FORMAT_AUTO:
                $format = $this->app->make(ThumbnailFormatService::class)->getAutomaticFormatForFile($savePath);
                break;
        }
        $thumbnailOptions = [
            'jpeg_quality' => $this->getJpegCompression(),
            'png_compression_level' => $this->getPngCompression(),
        ];
        $filesystem = $this->getStorageLocation()->getFileSystemObject();

        if ($mixed instanceof ImageInterface) {
            $image = $mixed;
        } else {
            $image = Image::open($mixed);
        }
        if ($fit) {
            $thumb = $image->thumbnail(new Box($width, $height), ImageInterface::THUMBNAIL_OUTBOUND);
            $filesystem->write(
                $savePath,
                $thumb->get($format, $thumbnailOptions)
            );
        } else {
            if ($height < 1) {
                $thumb = $image->thumbnail($image->getSize()->widen($width));
            } elseif ($width < 1) {
                $thumb = $image->thumbnail($image->getSize()->heighten($height));
            } else {
                $thumb = $image->thumbnail(new Box($width, $height));
            }
            $filesystem->write(
                $savePath,
                $thumb->get($format, $thumbnailOptions)
            );
        }
    }
796903
protected function spatiePdf(string $pdfPath, string $imagePath, array $options = [])
    {
        try {
            $this->containerUtil->isBundleActive('spatie/pdf-to-image');
        } catch (\Exception $e) {
            throw new \Exception('Package spatie/pdf-to-image is not installed. Please install or use another pdf ttranscoder.');
        }
        $imageExtension = pathinfo($imagePath, PATHINFO_EXTENSION);

        try {
            $pdf = new Pdf($pdfPath);

            if (isset($option['page']) && $options['page'] > 0) {
                $pdf->setPage($options['page']);
            }

            if (isset($option['compressionQuality']) && $options['compressionQuality'] > 0) {
                $pdf->setCompressionQuality($options['compressionQuality']);
            }

            if (isset($option['resolution']) && $options['resolution'] > 0) {
                $pdf->setResolution($options['resolution']);
            }

            if (!empty($imageExtension)) {
                $pdf->setOutputFormat($imageExtension);
            }
            $pdf->saveImage($imagePath);
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }
855048
public function save($filePath, $size = null, $compression = -1, $filters = -1)
    {
        return imagepng($this->getImage($size), $filePath, $compression, $filters);
    }
352749
private static void save(Bitmap src, String fileName, Bitmap.CompressFormat format, int quality) throws ImageSaveException {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileName);
            src.compress(format, quality, outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new ImageSaveException(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
263847
public function quality(int $q = 80, int $comp = 8){
    if ( $this->test() &&
      ((strtolower($this->get_extension()) === 'jpg') ||
        (strtolower($this->get_extension()) === 'jpeg'))
    ){
      if ( class_exists('\\Imagick') ){
        $this->img->setImageCompression($comp);
        $this->img->setImageCompressionQuality($q);
        $this->img->stripImage();
      }
    }
    return $this;
  }
244309
public function save($imageTargetFilePath, $quality = 100)
    {
        $resampleImageResource =& $this->getResampleImageResource();
        $resampleImageResource->setCompressionQuality($quality);
        $resampleImageResource->stripimage();

        $extension = pathinfo($imageTargetFilePath, PATHINFO_EXTENSION);

        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                $resampleImageResource->setImageFormat('jpg');
                break;

            case 'gif':
                $resampleImageResource->setImageFormat('gif');
                break;

            case 'png':
                $resampleImageResource->setImageFormat('png');
                $resampleImageResource->setImageAlphaChannel(\Gmagick::ALPHACHANNEL_ACTIVATE);
                $resampleImageResource->setBackgroundColor(new \GmagickPixel('transparent'));
                break;

            case 'webp':
                $resampleImageResource->setImageFormat('webp');
                $resampleImageResource->setImageAlphaChannel(\Gmagick::ALPHACHANNEL_ACTIVATE);
                $resampleImageResource->setBackgroundColor(new \GmagickPixel('transparent'));
                break;
        }

        try {

            $resampleImageResource->writeimage($imageTargetFilePath);

            return true;

        } catch (\GmagickException $e) {

            $this->errors[ $e->getCode() ] = $e->getMessage();

        }

        return false;
    }
393849
static function createForFile( $fileName, $filePath, $fileType = false )
    {
        $layer = new eZImageLayer();
        $layer->setStoredFile( $fileName, $filePath, $fileType );
        $layer->process();
        return $layer;
    }
27006
public function save($filename, $image_type = null, $quality = null, $permissions = null)
    {
        $image_type = $image_type ?: $this->source_type;
        if ($this->centered) {
            $dest_image = imagecreatetruecolor($this->ask_w, $this->ask_h);
        } else {
            $dest_image = imagecreatetruecolor($this->getDestWidth(), $this->getDestHeight());
        }
        imageinterlace($dest_image, $this->interlace);
        switch ($image_type) {
            case IMAGETYPE_GIF:
                $background = imagecolorallocatealpha($dest_image, 255, 255, 255, 1);
                imagecolortransparent($dest_image, $background);
                imagefill($dest_image, 0, 0, $background);
                imagesavealpha($dest_image, true);
                break;
            case IMAGETYPE_JPEG:
                $background = imagecolorallocate($dest_image, 255, 255, 255);
                if ($this->centered) {
                    imagefilledrectangle($dest_image, 0, 0, $this->ask_w, $this->ask_h, $background);
                } else {
                    imagefilledrectangle($dest_image, 0, 0, $this->getDestWidth(), $this->getDestHeight(), $background);
                }
                break;
            case IMAGETYPE_PNG:
                imagealphablending($dest_image, false);
                $background = imagecolorallocate($dest_image, 255, 255, 255);
                if ($this->centered) {
                    imagefilledrectangle($dest_image, 0, 0, $this->ask_w, $this->ask_h, $background);
                } else {
                    imagefilledrectangle($dest_image, 0, 0, $this->getDestWidth(), $this->getDestHeight(), $background);
                }
                    imagesavealpha($dest_image, true);
                break;
        }
        imagecopyresampled(
            $dest_image,
            $this->source_image,
            $this->dest_x,
            $this->dest_y,
            $this->source_x,
            $this->source_y,
            $this->getDestWidth(),
            $this->getDestHeight(),
            $this->source_w,
            $this->source_h
        );
        switch ($image_type) {
            case IMAGETYPE_GIF:
                imagegif($dest_image, $filename);
                break;
            case IMAGETYPE_JPEG:
                if ($quality === null) {
                    $quality = $this->quality_jpg;
                }
                imagejpeg($dest_image, $filename, $quality);
                break;
            case IMAGETYPE_PNG:
                if ($quality === null) {
                    $quality = $this->quality_png;
                }
                imagepng($dest_image, $filename, $quality);
                break;
        }
        if ($permissions) {
            chmod($filename, $permissions);
        }
        return $this;
    }
162109
private function make($filePath, array $params)
    {
        if (!is_null($this->basePath)) {
            $fileFullPath = FileHelper::normalizePath(Yii::getAlias($this->basePath . '/' . $filePath));
        } else {
            $fileFullPath = FileHelper::normalizePath($filePath);
        }

        $fileFullPath = urldecode($fileFullPath);

        if (!is_file($fileFullPath)) {
            return false;
        }

        $quality = isset($params['quality']) ? $params['quality'] : $this->options['quality'];

        $cacheFileName = md5($fileFullPath . serialize($params) . $quality . filemtime($fileFullPath));
        $cacheFileExt = strrchr($fileFullPath, '.');
        $cacheFileDir = '/' . substr($cacheFileName, 0, 2);
        $cacheFilePath = Yii::getAlias($this->cachePath) . $cacheFileDir;
        $cacheFile = $cacheFilePath . '/' . $cacheFileName . $cacheFileExt;
        $cacheUrl = str_replace('\\', '/', preg_replace('/^@[a-z]+/', '', $this->cachePath) . $cacheFileDir . '/'
            . $cacheFileName . $cacheFileExt);

        $cacheUrl = !is_null($this->prefixPath) ? $this->prefixPath . $cacheUrl : $cacheUrl;

        if (file_exists($cacheFile)) {
            if ($this->cacheExpire !== 0 && (time() - filemtime($cacheFile)) > $this->cacheExpire) {
                unlink($cacheFile);
            } else {
                return $cacheUrl;
            }
        }

        if (!is_dir($cacheFilePath)) {
            mkdir($cacheFilePath, 0755, true);
        }

        try{
            $this->image = Image::getImagine()->open($fileFullPath);
        }catch(\Imagine\Exception\RuntimeException $e){
            return null;
        }catch(\Imagine\Exception\InvalidArgumentException $e){
            return null;
        }

        foreach ($params as $key => $value) {
            switch ($key) {
                case self::FUNCTION_THUMBNAIL :
                    $this->thumbnail($value);
                    break;
                case self::FUNCTION_RESIZE :
                    $this->resize($value);
                    break;
                case self::FUNCTION_CROP :
                    $this->crop($value);
                    break;
                case self::FUNCTION_WATERMARK :
                    $this->watermark($value);
                    break;
            }
        }

        $this->image->save($cacheFile, [
            'quality' => $quality
        ]);

        if (array_key_exists(self::FUNCTION_COMPRESS, $params)) {
            if ($params[self::FUNCTION_COMPRESS] && !is_null($this->options['tinyPng']['apiKey'])) {
                $result = $this->tiny->compress($cacheFile);
                $result->writeTo($cacheFile);
            }
        }

        return $cacheUrl;
    }
454161
public static byte[] writeImageToBytes(BufferedImage image,
			String formatName, Float quality) throws IOException {
		byte[] bytes = null;
		if (quality != null) {
			bytes = compressAndWriteImageToBytes(image, formatName, quality);
		} else {
			bytes = writeImageToBytes(image, formatName);
		}
		return bytes;
	}
1115250
public static function storeAsset($filePath, $category, $storeAs = "")
    {
        // A sane default
        $mime = "application/octet-stream";

        $name = ($storeAs == "") ? basename($filePath) : $storeAs;

        // CSV is detected as text/plain - change this if.
        if (preg_match("/\\.csv$/i", $name)){
            $mime = "text/csv";
        } else {
            if (function_exists("finfo_open")) {
                $info = new \finfo(FILEINFO_MIME);
                $mime = $info->file($filePath);
            }
        }

        $provider = self::getProvider($category);

        try {
            $asset = $provider->createAssetFromFile($filePath, [
                "name" => $name,
                "size" => filesize($filePath),
                "mimeType" => $mime,
                "category" => $category
            ]);

            $asset->mimeType = $mime;
            return $asset;
        } catch (AssetException $er){
            Log::error("Error creating asset from file '$filePath': ".$er->getPrivateMessage());
            throw $er;
        }

        return null;
    }
117895
private function outputImage(string $imagePath = ''): void
    {
        $fPointer = \fopen($imagePath, 'rb');
        $this->sendCachingHeaders($imagePath);
        \header('Content-Type: '.$this->getImageContentType());
        \header('Content-Length: '.\filesize($imagePath));
        \fpassthru($fPointer);
        \fclose($fPointer);
        die();
    }
169033
public function save(string $path, string $name, ?string $extension = null, int $quality = 100): bool
    {
        if (false === is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if (null === $extension) {
            /** @var string $extension */
            $extension = $this->extension;
        }
        if (true === $this->encrypted) {
            file_put_contents($path . $name . '.' . self::FORMAT_WD_IMAGE, $this->workingData);
            return true;
        } elseif (0 !== imagetypes()) {
            $filename = $path . $name . '.' . $extension;
            switch (strtolower($extension)) {
                case self::FORMAT_GIF:
                    imagegif($this->workingData, $filename);
                    break;
                case self::FORMAT_JPEG:
                case self::FORMAT_JPG:
                    imagejpeg($this->workingData, $filename, $quality);
                    break;
                case self::FORMAT_PNG:
                    imagepng($this->workingData, $filename, (int)round(9 - ((9 * $quality) / 100)));
                    break;
                default:
                    throw new ImageException('Unsupported file type');
            }
            return false;
        }
    }
1155210
public function save($imgname, $type = null, $quality=80,$interlace = true){
        $this->img->save($imgname, $type, $quality,$interlace);
        return $this;
    }