@param string $pdfPath
@param string $imagePath

@throws \Exception

@return bool
182558
protected function alchemyPdf(string $pdfPath, string $imagePath, array $options = [])
    {
        try {
            $this->containerUtil->isBundleActive('alchemy/ghostscript');
        } catch (\Exception $e) {
            throw new \Exception('Package alchemy/ghostscript is not installed. Please install or use another pdf transcoder.');
        }
        $imageExtension = pathinfo($imagePath, PATHINFO_EXTENSION);
        $allowedExtensions = ['jpg', 'jpeg', 'png'];

        if (!\in_array($imageExtension, $allowedExtensions)) {
            throw new InvalidTypeException('Only one of the following file types is allowed: '.implode(
                ', ', $allowedExtensions)
            );
        }

        if ('jpg' === $imageExtension) {
            $imageExtension = 'jpeg';
        }
        $command = [
            '-sDEVICE='.$imageExtension,
            '-dNOPAUSE',
            '-dBATCH',
            '-dSAFER',
            '-sOutputFile='.$imagePath,
        ];

        if (isset($option['page']) && \is_int($options['page']) && $options['page'] > 0) {
            $command[] = sprintf('-dFirstPage=%d', $options['page']);
            $command[] = sprintf('-dLastPage=%d', $options['page']);
        }

        try {
            $command[] = $pdfPath;
            $transcoder = Transcoder::create();
            $transcoder->command($command);
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }
372996
public function getFileContent($filePath)
    {
        if ($this->repository->fileExists($filePath) === false) {
            throw new Exception(sprintf('The file "%s" cannot be found', $filePath));
        }
        return $this->repository->getFileContent($filePath);
    }
766496
private function getFile($filenameWithPath)
    {
        $explodedString = explode('\\', $filenameWithPath);
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . $explodedString[count($explodedString) - 1] . '"');
        readfile(ROOT . $filenameWithPath);
        exit; // $this->autoRender = false; is not enough!
    }
874757
protected function deleteUploadedImage($imageId, $thumbsPath, $imageSizes)
    {

        // delete physical files
        foreach ($imageSizes as $thumbSize => $options) {
            $thumbsFileName = $thumbsPath . DS . $imageId . $options['suffix'] . '.jpg';
            if (file_exists($thumbsFileName)) {
                unlink($thumbsFileName);
            }
        }
    }
180519
protected function _thumbnailImage(ImageWithImagineInterface $image, ImagePathInterface $path)
    {
        $this->assertImagine();
        $matches = null;
        if (!preg_match($this->pattern, $path->getPath(), $matches)) {
            return false;
        }
        
        if (is_callable($this->format)) {
            $format = call_user_func($this->format, $matches);
        } else {
            $format = $this->format;
        }
        
        if (false === $format) {
            // force a not found
            throw new ImageNotFoundException(sprintf('Image not found: %s', $path->getPath()));
        }
        
        if (is_null($format)) {
            // passthrough: we want the original image
            return true;
        }
        
        // not very LSP but handy
        if (!$image->getImagine()) {
            $image->setImagine($this->getImagine(), $this->getImagineOptions());
        }
        
        if (true === $format) {
            // we want the original image size but will trigger a save
            $image->deprecateBinaryContent();
            return true;
        }
        
        if (preg_match('/^(\<)?([0-9]+)x([0-9]+)$/', $format, $matches)) {
			$size = new \Imagine\Image\Box($matches[2], $matches[3]);
			$mode = $matches[1] == '<' ? \Imagine\Image\ImageInterface::THUMBNAIL_INSET : \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
		} elseif (preg_match('/^(\<)?([0-9]+)$/', $format, $matches)) {
			$size = new \Imagine\Image\Box($matches[2], $matches[2]);
			$mode = $matches[1] == '<' ? \Imagine\Image\ImageInterface::THUMBNAIL_INSET : \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
		} else {
			throw new ThumbnailRuleException(sprintf('Unsupported rule format: %s', (string)$format), ThumbnailRuleException::UNSUPPORTED_RULE_FORMAT);
		}
        
        /** @var IImage $animated */
        $animated = null;
        $imagine = $image->getImagine();
        if ($this->handleAnimatedGif($image, function (IImage $iimage) use ($imagine, $size, &$animated, $image) {
            $animated = $imagine->create($size);
            $animated->layers()->remove(0);
            $image->setImagineImage($animated);
            // we take first frame conf
            /** @var IImage $iframe */
            $iframe = $iimage->layers()[0];
            $options = [
                'flatten' => false,
                'animated' => true,
                'animated.delay' => $iframe->getImagick()->getImageDelay() * 10,
                'animated.loop' => $iframe->getImagick()->getImageIterations(),
            ];
            $image->setEphemeralImagineOptions($options);
        }, function (IImage $iframe) use ($size, $mode, &$animated) {
            $animated->layers()->add($iframe->thumbnail($size, $mode));
        }, function (IImage $iimage) {
            // nothing
        })) {
            // nothing
            return true;
        }
        $image->setImagineImage($image->getImagineImage()->thumbnail($size, $mode, $this->filter));
		return true;
    }
1205845
private function imageExists($imagePath, $imageSrc = null)
    {
        // If image name is sewhere parameter
        if (isset($imageSrc)) {
            // Form path to the image
            $imageFullPath = $this->formImagePath($imagePath, $imageSrc);
        } else {
            // Path was already set
            $imageFullPath = $imagePath;
        }

        // Call file service existence method
        return $this->fs->exists($imageFullPath);
    }
1246968
public static function isValid(string $filePath): bool
    {
        return self::myFilePathParse(
            DIRECTORY_SEPARATOR,
            $filePath,
            function ($p, $d, &$e) {
                return self::myPartValidator($p, $d, $e);
            });
    }
461799
function delete_dir($filepath)
	{
		if ( ! $this->_is_conn())
		{
			return false;
		}

		// Add a trailing slash to the file path if needed
		$filepath = preg_replace("/(.+?)\/*$/", "\\1/",  $filepath);

		$list = $this->list_files($filepath);

		if ($list !== false and count($list) > 0)
		{
			foreach ($list as $item)
			{
				// If we can't delete the item it's probaly a folder so
				// we'll recursively call delete_dir()
				if ( ! @ftp_delete($this->_conn_id, $item))
				{
					// don't recurse into current of parent directory
					if ( ! preg_match('/\/\.\.|\/\.$/', $item)) 
					{
						$this->delete_dir($item);
					}
				}
			}
		}

		$result = @ftp_rmdir($this->_conn_id, $filepath);

		if ($result === false)
		{
			if ($this->_debug == true)
			{
				throw new \FtpFileAccessException('Unable to delete');
			}
			return false;
		}

		return true;
	}
188946
public function save($savePath, $imageQuality = 95)
        {
            // If the image wasn't resized, fetch original image.
            if (!$this->imageResized) {
                $this->imageResized = $this->image;
            }

            // Get extension of the output file.
            $extension = Inflector::lower(File::extension($savePath));

            // Create and save an image based on it's extension.
            switch($extension)
            {
                case 'jpg':
                case 'jpeg':
                    if (imagetypes() & IMG_JPG) {
                        imagejpeg($this->imageResized, $savePath, $imageQuality);
                    }
                    break;

                case 'gif':
                    if (imagetypes() & IMG_GIF) {
                        imagegif($this->imageResized, $savePath);
                    }
                    break;

                case 'png':
                    // Scale quality from 0-100 to 0-9.
                    $scaleQuality = round(($imageQuality / 100) * 9);

                    // Invert quality setting as 0 is best, not 9.
                    $invertScaleQuality = 9 - $scaleQuality;

                    if (imagetypes() & IMG_PNG) {
                        imagepng($this->imageResized, $savePath, $invertScaleQuality);
                    }
                    break;

                default:
                    return false;
                    break;
            }

            // Remove the resource for the resized image.
            imagedestroy($this->imageResized);

            return true;
        }
181039
public function save($imageTargetFilePath, $quality = 100)
    {
        $resampleImageResource =& $this->getResampleImageResource();

        $extension = pathinfo($imageTargetFilePath, PATHINFO_EXTENSION);

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

            case 'gif':
                $resampleImageResource->setImageFormat('gif');
                $resampleImageResource->setCompression(\Imagick::COMPRESSION_UNDEFINED);
                break;

            case 'png':
                $resampleImageResource->setImageFormat('png');
                $resampleImageResource->setCompression(\Imagick::COMPRESSION_UNDEFINED);
                $resampleImageResource->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
                $resampleImageResource->setBackgroundColor(new \ImagickPixel('transparent'));
                break;

            case 'webp':
                $resampleImageResource->setImageFormat('webp');
                $resampleImageResource->setCompression(\Imagick::COMPRESSION_UNDEFINED);
                $resampleImageResource->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
                $resampleImageResource->setBackgroundColor(new \ImagickPixel('transparent'));
                break;
        }

        $resampleImageResource->setCompressionQuality($quality);
        $resampleImageResource->stripImage();

        return (bool)$resampleImageResource->writeImage($imageTargetFilePath);
    }
1042955
public function delete($filePath)
    {
        $relativePath = $this->fs->makePathRelative($filePath, $this->root);
        if (preg_match('!(^|/)\.\.!', $relativePath)) {
            throw new \RuntimeException("{$relativePath} does not seem to be managed by the filemanager");
        }
        if ($this->fs->exists($filePath)) {
            $this->fs->remove($filePath);
            $this->dispatchEvent(ResourceEvent::DELETED, $filePath);
            return true;
        }
        return false;
    }
338555
public function attachPdf($filepath)
    {
        $content = file_get_contents($filepath);
        $filename = basename($filepath);

        return $this->performEvent('attach', array('filename' => $filename, 'content' => base64_encode($content)));
    }
287394
protected function storeImage($imagePath)
    {
        /**
         * @var \Elcodi\Component\Media\Services\ImageManager                 $imageManager
         * @var \Gaufrette\Filesystem                                         $filesystem
         * @var \Elcodi\Component\Media\Transformer\FileIdentifierTransformer $fileIdentifierTransformer
         * @var \Doctrine\Common\Persistence\ObjectManager                    $imageObjectManager
         */
        $imageManager = $this->get('elcodi.manager.media_image');
        $imageObjectManager = $this->get('elcodi.object_manager.image');
        $filesystem = $this->get('elcodi.media_filesystem');
        $fileIdentifierTransformer = $this->get('elcodi.transformer.media_file_identifier');

        $image = $imageManager->createImage(new \Symfony\Component\HttpFoundation\File\File($imagePath));
        $imageObjectManager->persist($image);
        $imageObjectManager->flush($image);

        $filesystem->write(
            $fileIdentifierTransformer->transform($image),
            file_get_contents($imagePath),
            true
        );

        return $image;
    }
678198
public function drawImage($PDFFilePath = '', $outputPath = '', $dpi = 92, $page = 1, $imageType = 'JPEG')
    {
        $draw = new \PDFDraw();
        $draw->SetDPI($dpi);

        $doc = new \PDFDoc($PDFFilePath);
        $doc->InitSecurityHandler();
        $pg = $doc->GetPage($page);
        $draw->Export($pg, $outputPath, $imageType);
        $doc->Close();
    }
1327686
public function addPDF($filepath, $pages = 'all', $orientation = 'vertical') {
        if (file_exists($filepath)) {
            $file = new PdfObject;
            
            if (strtolower($pages) != 'all') {
                $file->pages = $this->_rewritepages($pages);
            }
            
            $file->orientation = $orientation;
            $file->path = $filepath;

            $this->_files[] = $file;
        } else {
            throw new Exception("Could not locate PDF on '$filepath'");
        }

        return $this;
    }
109766
public function createPdfCommand($targetPath)
    {
        $command    = $this->createCommand($this->url, 'pdf', ['path' => $targetPath]);
        if ($this->showBrowserHeaderAndFooter) {
            $command['options']['displayHeaderFooter'] = true;
        }
        if ($this->showBackground) {
            $command['options']['printBackground'] = true;
        }
        if ($this->landscape) {
            $command['options']['landscape'] = true;
        }
        if ($this->margins) {
            $command['options']['margin'] = [
                'top' => $this->margins['top'].'mm',
                'right' => $this->margins['right'].'mm',
                'bottom' => $this->margins['bottom'].'mm',
                'left' => $this->margins['left'].'mm',
            ];
        }
        if ($this->pages) {
            $command['options']['pageRanges'] = $this->pages;
        }
        if ($this->paperWidth > 0 && $this->paperHeight > 0) {
            $command['options']['width'] = $this->paperWidth.'mm';
            $command['options']['height'] = $this->paperHeight.'mm';
        }
        if ($this->format) {
            $command['options']['format'] = $this->format;
        }
        return $command;
    }
707653
public function process($filePath)
	{
		if ( ! is_string($filePath) && ! file_exists($filePath) && ! is_readable($filePath)) {
			$this->error = 'Failed to get image path';
			return;
		}

		$imageInfo = getimagesize($filePath);

		if ($imageInfo === false) {
			$this->error = 'Failed to get image information from path "' . $filePath . '"';
			return;
		}

		$this->width = $imageInfo[0];
		$this->height = $imageInfo[1];
		$this->type = $imageInfo[2];
		$this->bits = $imageInfo['bits'];
		$this->channels = (isset($imageInfo['channels']) ? $imageInfo['channels'] : null);
		$this->mime = $imageInfo['mime'];
		$this->path = $filePath;
		$this->size = filesize($filePath);
		$pathInfo = pathinfo($filePath);
		$this->name = $pathInfo['basename'];
		$this->directory = $pathInfo['dirname'];
		$this->extension = (isset($pathInfo['extension']) ? $pathInfo['extension'] : null);
	}