Function to compress image
@return boolean
@throws Exception
353083
public function compress_image(){
        
        //Send image array
        $array_img_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
        $new_image = null;
        $last_char = null;
        $image_extension = null;
        $destination_extension = null;
        $png_compression = null;
        $maxsize = 5245330;
        
        try{
            
            //If not found the file
            if(empty($this->file_url) && !file_exists($this->file_url)){
                throw new Exception('Please inform the image!');
                return false;
            }
            
            //Get image width, height, mimetype, etc..
            $image_data = getimagesize($this->file_url);
            //Set MimeType on variable
            $image_mime = $image_data['mime'];
            
            //Verifiy if the file is a image
            if(!in_array($image_mime, $array_img_types)){
                throw new Exception('Please send a image!');
                return false; 
            }
            
            //Get file size
            $image_size = filesize($this->file_url);
                                    
            //if image size is bigger than 5mb
            if($image_size >= $maxsize){
                throw new Exception('Please send a imagem smaller than 5mb!');
                return false;
            }
            
            //If not found the destination
            if(empty($this->new_name_image)){
                throw new Exception('Please inform the destination name of image!');
                return false;
            }
            
            //If not found the quality
            if(empty($this->quality)){
                throw new Exception('Please inform the quality!');
                return false;
            }

            //If not found the png quality
            $png_compression = (!empty($this->pngQuality)) ? $this->pngQuality : 9 ;
            
            $image_extension = pathinfo($this->file_url, PATHINFO_EXTENSION);
            //Verify if is sended a destination file name with extension
            $destination_extension = pathinfo($this->new_name_image, PATHINFO_EXTENSION); 
            //if empty
            if(empty($destination_extension)){
                $this->new_name_image = $this->new_name_image.'.'.$image_extension;
            }
            
            //Verify if folder destination isn´t empty
            if(!empty($this->destination)){
                
                //And verify the last one element of value
                $last_char = substr($this->destination, -1);
                
                if($last_char !== '/'){
                    $this->destination = $this->destination.'/';
                }
            }
            
            //Switch to find the file type
            switch ($image_mime){
                //if is JPG and siblings
                case 'image/jpeg':
                case 'image/pjpeg':
                    //Create a new jpg image
                    $new_image = imagecreatefromjpeg($this->file_url);
                    imagejpeg($new_image, $this->destination.$this->new_name_image, $this->quality);
                    break;
                //if is PNG and siblings
                case 'image/png':
                case 'image/x-png':
                    //Create a new png image
                    $new_image = imagecreatefrompng('conteudo/'.$this->file_url);
                    imagealphablending($new_image , false);
                    imagesavealpha($new_image , true);
                    imagepng($new_image, $this->destination.$this->new_name_image, $png_compression);
                    break;
                // if is GIF
                case 'image/gif':
                    //Create a new gif image
                    $new_image = imagecreatefromgif('conteudo/'.$this->file_url);
                    imagealphablending($new_image, false);
                    imagesavealpha($new_image, true);
                    imagegif($new_image, $this->destination.$this->new_name_image);
            }
            
        } catch (Exception $ex) {
            return $ex->getMessage();
        }
        
        //Return the new image resized
        return $this->new_name_image;
        
    }
94802
protected function compressioncheck($comptype)
    {
        if ($comptype === Archive::COMPRESS_GZIP && !function_exists('gzopen')) {
            throw new ArchiveIllegalCompressionException('No gzip support available');
        }

        if ($comptype === Archive::COMPRESS_BZIP && !function_exists('bzopen')) {
            throw new ArchiveIllegalCompressionException('No bzip2 support available');
        }
    }
137410
public function compressFile (string $filePath) : bool
    {
        $compressor = $this->getCompressor();

        if (null === $compressor)
        {
            return false;
        }

        $process = new Process(\array_merge($compressor, [$filePath]));
        $process->run();
        return $process->isSuccessful();
    }
1095007
private String compressImage(String imagePath, File destDirectory) {

        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(imagePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(imagePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        String resultFilePath = getFilename(imagePath, destDirectory);
        try {
            out = new FileOutputStream(resultFilePath);

            //  write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return resultFilePath;

    }
126752
public function compress($content)
    {
        $archive = $this->getArchive();
        if (!empty($archive)) {
            $file = bzopen($archive, 'w');
            if (!$file) {
                throw new Exception\RuntimeException("Error opening the archive '" . $archive . "'");
            }

            bzwrite($file, $content);
            bzclose($file);
            $compressed = true;
        } else {
            $compressed = bzcompress($content, $this->getBlocksize());
        }

        if (is_int($compressed)) {
            throw new Exception\RuntimeException('Error during compression');
        }

        return $compressed;
    }
284305
private function getCompressionMethod($method)
    {
        $this->log(LogLevel::DEBUG, 'Trying to find compression method {method}', ['method' => $method]);
        $compression_method = $this->getCompressionManager()->getCompressionAlgorithm($method);
        if (null === $compression_method) {
            $exception = new \InvalidArgumentException(sprintf('Compression method "%s" not supported', $method));
            $this->log(LogLevel::ERROR, 'Compression method {method} not supported', ['method' => $method, 'exception' => $exception]);
            throw $exception;
        }

        $this->log(LogLevel::DEBUG, 'Compression method {method} found', ['method' => $method, 'service' => $compression_method]);

        return $compression_method;
    }
693853
public function convertToPng()
    {
        $fileType = 'jpg';
        $target = sprintf(
            '%s/%s.%s',
            $this->getTarget(),
            $this->getName(),
            $fileType
        );
        $image = $this->createImageFrom($this->getFilePath());
        imagejpeg($image, $target, 100);
        imagedestroy($image);
        $this->setCovertVars([
            'ext' => $fileType,
            'filepath' => $target
        ]);
        return $this;
    }
1220106
public function get($format = 'png')
    {
        $this->create();

        if ($format == 'jpg') {
            $format = 'jpeg';
        }

        if (!in_array($format, $this->image_types_available)) {
            $format = $this->image_type;
        }

        if (!function_exists('image'.$format)) {
            throw new Exception('QRCode: function image'.$format.' does not exists.');
        }

        ob_start();
        $success = call_user_func('image'.$format, $this->image);

        if ($success === false) {
            throw new Exception('QRCode: function image'.$format.' failed.');
        }

        $content = ob_get_clean();

        return $content;
    }
1256155
public function resize()
    {
        $src = $this->rootDir.DS.str_replace(['/', '\\'], DS, $this->imagePath);   /* read the source image */

        if (!file_exists($src)) {
            throw new \Exception("File not found in given path $src.");
        }

        $info = getimagesize($src); // get the image size
        $path = pathinfo($src);
        $extension = strtolower($path['extension']);

        if (!in_array($extension, $this->imageTypes)) {
            throw new \Exception('File type not supported!');
        }

        $thumbName = is_null($this->thumbName)
            ? $path['basename']
            : $this->thumbName.'.'.$path['extension'];

        $sourceImage = $this->imageCreateFrom(($extension == 'gif') ? 'jpeg' : $extension, $src);
        $thumbImg = $this->changeDimensions($sourceImage, $this->fixedWidth, $this->fixedHeight);
        $this->image($extension, $thumbImg, $thumbName);

        return true;
    }
52605
public function compress()
    {
        if (!$this->collection->schema) {
            $this->compressed =& $this->data;

            return;
        }
        if ($this->state !== 'compressed' && $this->collection) {
            $this->compressed = $this->applyCompression($this->data);
            $this->asDotSyntax();
            $this->state = 'compressed';
        }
    }
440288
public function writeInOutput()
  {
    $image = $this->applyFilters();

    if ($this->extension == self::IMAGE_TYPE_JPG) {
      header('Content-Type: image/jpg');
      imagejpeg($image, null, $this->jpgQuality);
    } else if ($this->extension == self::IMAGE_TYPE_PNG) {
      header('Content-Type: image/png');
      imagepng($image, null, $this->pngCompression);
    } else {
      throw new \Exception('Impossible de générer l\'image : extension non supportée');
    }
  }
1155001
public function save() {
        try {
            $this->file->upload();

            $filename = $this->file->getNameWithExtension();

            if ($this->function) {
                $func = $this->function;
                $fileSource = $this->dest . '/' . $this->file->getNameWithExtension();
                $filename = $this->alternaiveName ? $this->alternaiveName . '.' . $this->file->getExtension() : $this->file->getNameWithExtension();

                $image = new ImageResize($fileSource);
                call_user_func_array(array($image, $func), $this->params);
                $image->save($this->dest . '/' . $filename);
            }
            return $filename;
        } catch (\Exception $e) {
            $this->errors = $e->getMessage();
            return false;
        }

        return true;
    }
1168058
public function save()
    {
        $dir = dirname($this->path);

        if (!is_dir($dir)) {
            $mask = @umask(0);
            $result = @mkdir($dir, $this->dirMode, true);
            @umask($mask);

            if (!$result) {
                throw new Exception("Unable to create the directory '$dir'.");
            }
        }

        if (@file_put_contents($this->path, $this->content) === false) {
            throw new Exception("Unable to write the file '{$this->path}'.");
        }

        $mask = @umask(0);
        @chmod($this->path, $this->mode);
        @umask($mask);

        return true;
    }
762242
public function isImage() {
		try {
			if (!function_exists('exif_imagetype') && !function_exists('Jodit\exif_imagetype')) {
				function exif_imagetype($filename) {
					if ((list(, , $type) = getimagesize($filename)) !== false) {
						return $type;
					}

					return false;
				}
			}

			return in_array(exif_imagetype($this->getPath()), [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP]);
		} catch (\Exception $e) {
			return false;
		}
	}
1226600
private function fileCompress()
    {
        if ($this->file && $this->file->getTmp()) {
            $compression = $this->file->getCompression();
            if ($compression && in_array($compression, ['tar.gz', 'tar.bz2', 'zip'])) {
                // Discern new tmp file name (with compression applied).
                $target   = $this->fileGenerateTmp($compression);
                $fileName = $this->getFileName();
                try {
                    switch ($compression) {
                        case 'tar.gz':
                            $phar = new \PharData($target);
                            $phar->addFile($this->file->getTmp(), $fileName);
                            $phar->compress(\Phar::GZ, $compression);
                            $target = $phar->getRealPath();
                            break;

                        case 'tar.bz2':
                            $phar = new \PharData($target);
                            $phar->addFile($this->file->getTmp(), $fileName);
                            $phar->compress(\Phar::BZ2, $compression);
                            $target = $phar->getRealPath();
                            break;

                        default:
                        case 'zip':
                            $zip = new \ZipArchive();
                            if (true !== $zip->open($target, \ZipArchive::CREATE)) {
                                throw new ContactClientException(
                                    'Cound not open zip '.$target,
                                    Codes::HTTP_INTERNAL_SERVER_ERROR,
                                    null,
                                    Stat::TYPE_ERROR,
                                    false
                                );
                            }
                            $zip->addFile($this->file->getTmp(), $fileName);
                            $zip->close();
                            break;
                    }
                    $this->file->setTmp($target);
                    $this->setLogs($target, 'fileCompressed');
                } catch (\Exception $e) {
                    throw new ContactClientException(
                        'Could not create compressed file '.$target,
                        Codes::HTTP_INTERNAL_SERVER_ERROR,
                        $e,
                        Stat::TYPE_ERROR,
                        false
                    );
                }
            } else {
                $this->setLogs(false, 'fileCompressed');
            }
        }

        return $this;
    }
808070
protected function saveImage()
    {
        if (!$this->image) {
            return parent::path(false);
        }

        $this->filter();

        if (isset($this->result)) {
            return $this->result;
        }

        if (!$this->debug_watermarked && $this->get('debug')) {
            $ratio = $this->get('ratio');
            if (!$ratio) {
                $ratio = 1;
            }

            $locator = Grav::instance()['locator'];
            $overlay = $locator->findResource("system://assets/responsive-overlays/{$ratio}x.png") ?: $locator->findResource('system://assets/responsive-overlays/unknown.png');
            $this->image->merge(ImageFile::open($overlay));
        }

        return $this->image->cacheFile($this->format, $this->quality, false, [$this->get('width'), $this->get('height'), $this->get('modified')]);
    }
111363
public function isImage()
	{
		$mime = $this->getMimeType();
		
		// The $imageMimes property contains an array of file extensions and
		// their associated MIME types. We will loop through them and look for 
		// the MIME type of the current SymfonyUploadedFile.
		foreach ($this->imageMimes as $imageMime)
		{
			if (in_array($mime, (array) $imageMime))
			{
				return true;
			}
		}

		return false;
	}