예제 #1
0
 /**
  * {@inheritDoc}
  */
 public function getImage($relativePath, $filter)
 {
     $eventManager = $this->getEventManager();
     $eventManager->trigger(__FUNCTION__, $this, ['relativePath' => $relativePath, 'filter' => $filter]);
     $filterOptions = $this->filterManager->getFilterOptions($filter);
     $binary = $this->loaderManager->loadBinary($relativePath, $filter);
     if (isset($filterOptions['format'])) {
         $format = $filterOptions['format'];
     } else {
         $format = $binary->getFormat() ?: 'png';
     }
     $imageOutputOptions = [];
     if (isset($filterOptions['quality'])) {
         $imageOutputOptions['quality'] = $filterOptions['quality'];
     }
     if ($format === 'gif' && $filterOptions['animated']) {
         $imageOutputOptions['animated'] = $filterOptions['animated'];
     }
     if ($this->cacheManager->isCachingEnabled($filter, $filterOptions) && $this->cacheManager->cacheExists($relativePath, $filter, $format)) {
         $imagePath = $this->cacheManager->getCachePath($relativePath, $filter, $format);
         $filteredImage = $this->imagine->open($imagePath);
     } else {
         $image = $this->imagine->load($binary->getContent());
         $filteredImage = $this->filterManager->getFilter($filter)->apply($image);
         if ($this->cacheManager->isCachingEnabled($filter, $filterOptions)) {
             $this->cacheManager->createCache($relativePath, $filter, $filteredImage, $format, $imageOutputOptions);
         }
     }
     $args = ['relativePath' => $relativePath, 'filter' => $filter, 'filteredImage' => $filteredImage, 'format' => $format];
     $eventManager->trigger(__FUNCTION__ . '.post', $this, $args);
     return ['image' => $filteredImage, 'format' => $format, 'imageOutputOptions' => $imageOutputOptions];
 }
 /**
  * @param Request $request
  * @param string  $filename
  *
  * @throws NotFoundHttpException If media is not found
  *
  * @return Response
  */
 public function showAction(Request $request, $filename)
 {
     if (!$this->filesystem->has($filename)) {
         throw new NotFoundHttpException(sprintf('Media "%s" not found', $filename));
     }
     $response = new Response($content = $this->filesystem->read($filename));
     $mime = $this->filesystem->mimeType($filename);
     if (($filter = $request->query->get('filter')) && null !== $mime && 0 === strpos($mime, 'image')) {
         try {
             $cachePath = $this->cacheManager->resolve($request, $filename, $filter);
             if ($cachePath instanceof Response) {
                 $response = $cachePath;
             } else {
                 $image = $this->imagine->load($content);
                 $response = $this->filterManager->get($request, $filter, $image, $filename);
                 $response = $this->cacheManager->store($response, $cachePath, $filter);
             }
         } catch (\RuntimeException $e) {
             if (0 === strpos($e->getMessage(), 'Filter not defined')) {
                 throw new HttpException(404, sprintf('The filter "%s" cannot be found', $filter), $e);
             }
             throw $e;
         }
     }
     if ($mime) {
         $response->headers->set('Content-Type', $mime);
     }
     return $response;
 }
 /**
  * @param BinaryInterface $binary
  * @param array           $config
  *
  * @throws \InvalidArgumentException
  *
  * @return Binary
  */
 public function apply(BinaryInterface $binary, array $config)
 {
     $config = array_replace(array('filters' => array(), 'quality' => 100, 'animated' => false), $config);
     $image = $this->imagine->load($binary->getContent());
     foreach ($config['filters'] as $eachFilter => $eachOptions) {
         if (!isset($this->loaders[$eachFilter])) {
             throw new \InvalidArgumentException(sprintf('Could not find filter loader for "%s" filter type', $eachFilter));
         }
         $image = $this->loaders[$eachFilter]->load($image, $eachOptions);
     }
     $options = array('quality' => $config['quality']);
     if (isset($config['jpeg_quality'])) {
         $options['jpeg_quality'] = $config['jpeg_quality'];
     }
     if (isset($config['png_compression_level'])) {
         $options['png_compression_level'] = $config['png_compression_level'];
     }
     if (isset($config['png_compression_filter'])) {
         $options['png_compression_filter'] = $config['png_compression_filter'];
     }
     if ($binary->getFormat() === 'gif' && $config['animated']) {
         $options['animated'] = $config['animated'];
     }
     $filteredFormat = isset($config['format']) ? $config['format'] : $binary->getFormat();
     $filteredContent = $image->get($filteredFormat, $options);
     $filteredMimeType = $filteredFormat === $binary->getFormat() ? $binary->getMimeType() : $this->mimeTypeGuesser->guess($filteredContent);
     return $this->applyPostProcessors(new Binary($filteredContent, $filteredMimeType, $filteredFormat), $config);
 }
 /**
  * {@inheritDoc}
  */
 public function find($id)
 {
     $image = $this->dm->getRepository($this->class)->findAll()->getCollection()->findOne(array("_id" => new \MongoId($id)));
     if (!$image) {
         throw new NotFoundHttpException(sprintf('Source image not found with id "%s"', $id));
     }
     return $this->imagine->load($image['file']->getBytes());
 }
 /**
  * {@inheritdoc}
  */
 public function resize(MediaInterface $media, File $in, File $out, $format, array $settings)
 {
     if (!isset($settings['width'])) {
         throw new \RuntimeException(sprintf('Width parameter is missing in context "%s" for provider "%s"', $media->getContext(), $media->getProviderName()));
     }
     $image = $this->adapter->load($in->getContent());
     $content = $image->thumbnail($this->getBox($media, $settings), $this->mode)->get($format, array('quality' => $settings['quality']));
     $out->setContent($content, $this->metadata->get($media, $out->getName()));
 }
예제 #6
0
 /**
  * {@inheritdoc}
  */
 public function convert(FileVersion $fileVersion, $formatKey)
 {
     $content = $this->storage->loadAsString($fileVersion->getName(), $fileVersion->getVersion(), $fileVersion->getStorageOptions());
     $extractedImage = $this->mediaImageExtractor->extract($content);
     try {
         $image = $this->imagine->load($extractedImage);
     } catch (RuntimeException $e) {
         throw new InvalidFileTypeException($e->getMessage());
     }
     $image = $this->toRGB($image);
     $format = $this->getFormat($formatKey);
     $cropParameters = $this->getCropParameters($image, $fileVersion->getFormatOptions()->get($formatKey), $this->formats[$formatKey]);
     if (isset($cropParameters)) {
         $image = $this->applyFormatCrop($image, $cropParameters);
     }
     if (isset($format['scale']) && $format['scale']['mode'] !== ImageInterface::THUMBNAIL_INSET) {
         $image = $this->applyFocus($image, $fileVersion, $format['scale']);
     }
     if (isset($format['scale'])) {
         $image = $this->applyScale($image, $format['scale']);
     }
     if (isset($format['transformations'])) {
         $image = $this->applyTransformations($image, $format['transformations']);
     }
     $image->strip();
     // Set Interlacing to plane for smaller image size.
     if (count($image->layers()) == 1) {
         $image->interlace(ImageInterface::INTERLACE_PLANE);
     }
     $imagineOptions = $format['options'];
     $imageExtension = $this->getImageExtension($fileVersion->getName());
     return $image->get($imageExtension, $this->getOptionsFromImage($image, $imageExtension, $imagineOptions));
 }
예제 #7
0
 /**
  * @param BinaryInterface $binary
  * @param array $config
  *
  * @throws \InvalidArgumentException
  *
  * @return Binary
  */
 public function apply(BinaryInterface $binary, array $config)
 {
     $config = array_replace(array('filters' => array(), 'quality' => 100, 'animated' => false), $config);
     $image = $this->imagine->load($binary->getContent());
     foreach ($config['filters'] as $eachFilter => $eachOptions) {
         if (!isset($this->loaders[$eachFilter])) {
             throw new \InvalidArgumentException(sprintf('Could not find filter loader for "%s" filter type', $eachFilter));
         }
         $image = $this->loaders[$eachFilter]->load($image, $eachOptions);
     }
     $options = array('quality' => $config['quality']);
     if ($binary->getFormat() === 'gif' && $config['animated']) {
         $options['animated'] = $config['animated'];
     }
     $filteredContent = $image->get($binary->getFormat(), $options);
     return new Binary($filteredContent, $binary->getMimeType(), $binary->getFormat());
 }
예제 #8
0
 /**
  * Draw $image on $this->resultImage.
  *
  * @param string $image Image blob.
  * @param Point  $point The point where to draw $image.
  *
  * @return void
  */
 protected function drawImage($image, Point $point)
 {
     try {
         $this->resultImage->paste($this->imagine->load($image), $point);
     } catch (\Exception $exception) {
         // Most likely an exception about a out of bounds past, we'll just ignore that
     }
 }
 /**
  * {@inheritDoc}
  */
 public function find($path)
 {
     $name = $this->wrapperPrefix . $path;
     /*
      * This looks strange, but at least in PHP 5.3.8 it will raise an E_WARNING if the 4th parameter is null.
      * fopen() will be called only once with the correct arguments.
      *
      * The error suppression is solely to determine whether the file exists.
      * file_exists() is not used as not all wrappers support stat() to actually check for existing resources.
      */
     if ($this->context && !($resource = @fopen($name, 'r', null, $this->context)) || !($resource = @fopen($name, 'r'))) {
         throw new NotFoundHttpException('Source image not found.');
     }
     // Closing the opened stream to avoid locking of the resource to find.
     fclose($resource);
     return $this->imagine->load(file_get_contents($name, null, $this->context));
 }
예제 #10
0
 /**
  * Loads an image from a file system path.
  *
  * @param string $path
  *
  * @throws Exception
  * @return Image
  */
 public function loadImage($path)
 {
     if (!IOHelper::fileExists($path)) {
         throw new Exception(Craft::t('No file exists at the path “{path}”', array('path' => $path)));
     }
     if (!craft()->images->checkMemoryForImage($path)) {
         throw new Exception(Craft::t("Not enough memory available to perform this image operation."));
     }
     $extension = IOHelper::getExtension($path);
     if ($extension === 'svg') {
         if (!craft()->images->isImagick()) {
             throw new Exception(Craft::t('The file “{path}” does not appear to be an image.', array('path' => $path)));
         }
         $svg = IOHelper::getFileContents($path);
         if ($this->minSvgWidth !== null && $this->minSvgHeight !== null) {
             // Does the <svg> node contain valid `width` and `height` attributes?
             list($width, $height) = ImageHelper::parseSvgSize($svg);
             if ($width !== null && $height !== null) {
                 $scale = 1;
                 if ($width < $this->minSvgWidth) {
                     $scale = $this->minSvgWidth / $width;
                 }
                 if ($height < $this->minSvgHeight) {
                     $scale = max($scale, $this->minSvgHeight / $height);
                 }
                 $width = round($width * $scale);
                 $height = round($height * $scale);
                 if (preg_match(ImageHelper::SVG_WIDTH_RE, $svg) && preg_match(ImageHelper::SVG_HEIGHT_RE, $svg)) {
                     $svg = preg_replace(ImageHelper::SVG_WIDTH_RE, "\${1}{$width}px\"", $svg);
                     $svg = preg_replace(ImageHelper::SVG_HEIGHT_RE, "\${1}{$height}px\"", $svg);
                 } else {
                     $svg = preg_replace(ImageHelper::SVG_TAG_RE, "\${1} width=\"{$width}px\" height=\"{$height}px\" \${2}", $svg);
                 }
             }
         }
         try {
             $this->_image = $this->_instance->load($svg);
         } catch (\Imagine\Exception\RuntimeException $e) {
             // Invalid SVG. Maybe it's missing its DTD?
             $svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $svg;
             $this->_image = $this->_instance->load($svg);
         }
     } else {
         $imageInfo = @getimagesize($path);
         if (!is_array($imageInfo)) {
             throw new Exception(Craft::t('The file “{path}” does not appear to be an image.', array('path' => $path)));
         }
         $this->_image = $this->_instance->open($path);
     }
     $this->_extension = $extension;
     $this->_imageSourcePath = $path;
     if ($this->_extension == 'gif') {
         if (!craft()->images->isGd() && $this->_image->layers()) {
             $this->_isAnimatedGif = true;
         }
     }
     return $this;
 }
예제 #11
0
 /**
  * @param BinaryInterface $binary
  * @param array           $config
  *
  * @throws \InvalidArgumentException
  *
  * @return Binary
  */
 public function apply(BinaryInterface $binary, array $config)
 {
     $config = array_replace(array('filters' => array(), 'quality' => 100, 'animated' => false), $config);
     if ($binary instanceof FileBinaryInterface) {
         $image = $this->imagine->open($binary->getPath());
     } else {
         $image = $this->imagine->load($binary->getContent());
     }
     foreach ($config['filters'] as $eachFilter => $eachOptions) {
         if (!isset($this->loaders[$eachFilter])) {
             throw new \InvalidArgumentException(sprintf('Could not find filter loader for "%s" filter type', $eachFilter));
         }
         $prevImage = $image;
         $image = $this->loaders[$eachFilter]->load($image, $eachOptions);
         // If the filter returns a different image object destruct the old one because imagick keeps consuming memory if we don't
         // See https://github.com/liip/LiipImagineBundle/pull/682
         if ($prevImage !== $image && method_exists($prevImage, '__destruct')) {
             $prevImage->__destruct();
         }
     }
     $options = array('quality' => $config['quality']);
     if (isset($config['jpeg_quality'])) {
         $options['jpeg_quality'] = $config['jpeg_quality'];
     }
     if (isset($config['png_compression_level'])) {
         $options['png_compression_level'] = $config['png_compression_level'];
     }
     if (isset($config['png_compression_filter'])) {
         $options['png_compression_filter'] = $config['png_compression_filter'];
     }
     if ($binary->getFormat() === 'gif' && $config['animated']) {
         $options['animated'] = $config['animated'];
     }
     $filteredFormat = isset($config['format']) ? $config['format'] : $binary->getFormat();
     $filteredContent = $image->get($filteredFormat, $options);
     $filteredMimeType = $filteredFormat === $binary->getFormat() ? $binary->getMimeType() : $this->mimeTypeGuesser->guess($filteredContent);
     // We are done with the image object so we can destruct the this because imagick keeps consuming memory if we don't
     // See https://github.com/liip/LiipImagineBundle/pull/682
     if (method_exists($image, '__destruct')) {
         $image->__destruct();
     }
     return $this->applyPostProcessors(new Binary($filteredContent, $filteredMimeType, $filteredFormat), $config);
 }
예제 #12
0
 /**
  * Creates an image object
  *
  * @param array|\Imagine\Image\ImageInterface $source
  * @throws \InvalidArgumentException On unsupported source type
  * @return \Imagine\Image\ImageInterface
  */
 public function create($source)
 {
     if ($source instanceof ImageInterface) {
         return $source;
     }
     if (isset($source['file'])) {
         return $this->imagine->open($source['file']);
     }
     if (isset($source['data'])) {
         return $this->imagine->load($source['data']);
     }
     if (isset($source['resource'])) {
         return $this->imagine->read($source['resource']);
     }
     if (isset($source['width']) && isset($source['height'])) {
         return $this->imagine->create(new Box($source['width'], $source['height']));
     }
     throw new InvalidArgumentException();
 }
예제 #13
0
 /**
  * Load an image from an SVG string.
  *
  * @param $svgContent
  *
  * @return Image
  */
 public function loadFromSVG($svgContent)
 {
     try {
         $this->_image = $this->_instance->load($svgContent);
     } catch (\Imagine\Exception\RuntimeException $e) {
         // Invalid SVG. Maybe it's missing its DTD?
         $svgContent = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $svgContent;
         $this->_image = $this->_instance->load($svgContent);
     }
     return $this;
 }
예제 #14
0
 /**
  * Set size of file, if it's image, set width and height.
  *
  * @param MediaInterface $media
  *
  * @return MediaInterface
  */
 public function setSizeWidthAndHeight(MediaInterface $media)
 {
     $key = $this->originalDir . '/' . $media->getReference();
     $media->setSize($this->filesystemManipulator->size($key));
     if ($media->getType() === $media::IMAGE) {
         $image = $this->imagine->load($this->filesystemManipulator->read($key));
         $size = $image->getSize();
         $media->setWidth($size->getWidth());
         $media->setHeight($size->getHeight());
     }
     return $this;
 }
예제 #15
0
 /**
  * {@inheritDoc}
  */
 public function normalizeImage($name, $content, $width, $height)
 {
     $extension = $this->getExtension($name);
     $image = $this->imagine->load($content);
     $size = $image->getSize();
     $box = new \Imagine\Image\Box($size->getWidth(), $size->getHeight());
     if ($size->getWidth() >= $size->getHeight() && $size->getWidth() > $width) {
         return $image->resize($box->widen($width))->get($extension);
     } elseif ($size->getWidth() < $size->getHeight() && $size->getHeight() > $height) {
         return $image->resize($box->heighten($height))->get($extension);
     }
     return $image->get($extension);
 }
 /**
  * @param string $path
  *
  * @return \Imagine\Image\ImageInterface
  */
 public function find($path)
 {
     $image = $this->manager->find($this->class, $this->mapPathToId($path));
     if (!$image) {
         // try to find the image without extension
         $info = pathinfo($path);
         $name = $info['dirname'] . '/' . $info['filename'];
         // attempt to determine available format
         foreach ($this->formats as $format) {
             if ($image = $this->manager->find($this->class, $this->mapPathToId($name . '.' . $format))) {
                 break;
             }
         }
         // maybe the image has an id without extension
         if (!$image) {
             $image = $this->manager->find($this->class, $this->mapPathToId($name));
         }
     }
     if (!$image) {
         throw new NotFoundHttpException(sprintf('Source image not found with id "%s"', $path));
     }
     return $this->imagine->load(stream_get_contents($this->getStreamFromImage($image)));
 }
예제 #17
0
 protected function doDrawBarcode($x, $y, Barcode $barcode)
 {
     $renderer = new \Zend\Barcode\Renderer\Image(array());
     $imageResource = imagecreate($barcode->getWidth(true) + 1, $barcode->getHeight(true) + 1);
     $renderer->setResource($imageResource);
     $renderer->setBarcode($barcode);
     $renderer->draw();
     ob_start();
     imagepng($imageResource);
     $image = ob_get_clean();
     @imagedestroy($image);
     $image = $this->imagine->load($image);
     $image = $image->resize(new Box($image->getSize()->getWidth() / 2, $image->getSize()->getHeight() / 2));
     list($currentImage, $point) = $this->getCurrentClip();
     $currentImage->paste($image, $this->translatePoint($point, $x, $this->convertYCoord($y)));
 }
예제 #18
0
 public function getImagineImage(ImagineInterface $imagine, FontCollection $fontCollection, $width, $height)
 {
     $fontPath = $fontCollection->getFontById($this->font)->getPath();
     if ($this->getAbsoluteSize() !== null) {
         $fontSize = $this->getAbsoluteSize();
     } elseif ($this->getRelativeSize() !== null) {
         $fontSize = (int) $this->getRelativeSize() / 100 * $height;
     } else {
         throw new \LogicException('Either relative or absolute watermark size must be set!');
     }
     if (true || !class_exists('ImagickDraw')) {
         // Fall back to ugly image.
         $palette = new \Imagine\Image\Palette\RGB();
         $font = $imagine->font($fontPath, $fontSize, $palette->color('#000'));
         $box = $font->box($this->getText());
         $watermarkImage = $imagine->create($box, $palette->color('#FFF'));
         $watermarkImage->draw()->text($this->text, $font, new \Imagine\Image\Point(0, 0));
     } else {
         // CURRENTLY DISABLED.
         // Use nicer Imagick implementation.
         // Untested!
         // @todo Test and implement it!
         $draw = new \ImagickDraw();
         $draw->setFont($fontPath);
         $draw->setFontSize($fontSize);
         $draw->setStrokeAntialias(true);
         //try with and without
         $draw->setTextAntialias(true);
         //try with and without
         $draw->setFillColor('#fff');
         $textOnly = new \Imagick();
         $textOnly->newImage(1400, 400, "transparent");
         //transparent canvas
         $textOnly->annotateImage($draw, 0, 0, 0, $this->text);
         //Create stroke
         $draw->setFillColor('#000');
         //same as stroke color
         $draw->setStrokeColor('#000');
         $draw->setStrokeWidth(8);
         $strokeImage = new \Imagick();
         $strokeImage->newImage(1400, 400, "transparent");
         $strokeImage->annotateImage($draw, 0, 0, 0, $this->text);
         //Composite text over stroke
         $strokeImage->compositeImage($textOnly, \Imagick::COMPOSITE_OVER, 0, 0, \Imagick::CHANNEL_ALPHA);
         $strokeImage->trimImage(0);
         //cut transparent border
         $watermarkImage = $imagine->load($strokeImage->getImageBlob());
         //$strokeImage->resizeImage(300,0, \Imagick::FILTER_CATROM, 0.9, false); //resize to final size
     }
     return $watermarkImage;
 }