/** * @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 string $imagePath * @param string[]|ConfigInterface[] $versionsConfig * @param string $outputDir * @param string $imageUniqueName * * @return string[] */ public function createImageVersions($imagePath, $versionsConfig, $outputDir = null, $imageUniqueName = null) { if ($outputDir === null) { $outputDir = $this->outputDir; } if ($imageUniqueName === null) { $imageUniqueName = $this->getUniqueName($imagePath); } $versions = []; $imageExt = pathinfo($imagePath, PATHINFO_EXTENSION); foreach ($versionsConfig as $versionName => $versionConfig) { if (is_string($versionConfig)) { $config = $this->configParser->parse($versionConfig); } elseif ($versionConfig instanceof ConfigInterface) { $config = $versionConfig; } else { throw new InvalidConfigException('Config must be a string or implement happyproff\\Kartinki\\Interfaces\\ConfigInterface.'); } $versionFilename = $imageUniqueName . self::NAME_SEPARATOR . $versionName . '.' . $imageExt; $image = $this->processor->read(fopen($imagePath, 'r')); $version = $this->createImageVersion($image, $config); $version->save($outputDir . '/' . $versionFilename, ['jpeg_quality' => $config->getQuality()]); unset($version); $versions[$versionName] = $versionFilename; } return $versions; }
/** * @param ImageResourceInterface $resource * @return boolean */ public function process(ImageResourceInterface $resource) { $image = $this->imageService->open($resource->getPath()); $mode = ImagineImageInterface::THUMBNAIL_INSET; $image->thumbnail($this->imageBox, $mode)->save($this->pathFilter->filter($resource->getPath()), array('format' => $resource->getExt(), 'quality' => '100')); return true; }
/** * @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 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]; }
/** * {@inheritDoc} */ public function find($path) { if (false !== strpos($path, '/../') || 0 === strpos($path, '../')) { throw new NotFoundHttpException(sprintf("Source image was searched with '%s' out side of the defined root path", $path)); } $file = $this->rootPath . '/' . ltrim($path, '/'); $info = $this->getFileInfo($file); $absolutePath = $info['dirname'] . DIRECTORY_SEPARATOR . $info['basename']; $name = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename']; $targetFormat = null; // set a format if an extension is found and is allowed if (isset($info['extension']) && (empty($this->formats) || in_array($info['extension'], $this->formats))) { $targetFormat = $info['extension']; } if (empty($targetFormat) || !file_exists($absolutePath)) { // attempt to determine path and format $absolutePath = null; foreach ($this->formats as $format) { if ($targetFormat !== $format && file_exists($name . '.' . $format)) { $absolutePath = $name . '.' . $format; break; } } if (!$absolutePath) { if (!empty($targetFormat) && is_file($name)) { $absolutePath = $name; } else { throw new NotFoundHttpException(sprintf('Source image not found in "%s"', $file)); } } } return $this->imagine->open($absolutePath); }
/** * Crop and resize an image * * @param string $source Path to source image * @param string $destination Path to destination * If not set, will modify the source image * @param array $params An array of cropping/resizing parameters * - INT 'w' represents the width of the new image * With upscaling disabled, this is the maximum width * of the new image (in case the source image is * smaller than the expected width) * - INT 'h' represents the height of the new image * With upscaling disabled, this is the maximum height * - INT 'x1', 'y1', 'x2', 'y2' represent optional cropping * coordinates. The source image will first be cropped * to these coordinates, and then resized to match * width/height parameters * - BOOL 'square' - square images will fill the * bounding box (width x height). In Imagine's terms, * this equates to OUTBOUND mode * - BOOL 'upscale' - if enabled, smaller images * will be upscaled to fit the bounding box. * @return bool */ public function resize($source, $destination = null, array $params = []) { if (!isset($destination)) { $destination = $source; } try { $image = $this->imagine->open($source); $width = $image->getSize()->getWidth(); $height = $image->getSize()->getHeight(); $params = $this->normalizeResizeParameters($width, $height, $params); $max_width = elgg_extract('w', $params); $max_height = elgg_extract('h', $params); $x1 = (int) elgg_extract('x1', $params, 0); $y1 = (int) elgg_extract('y1', $params, 0); $x2 = (int) elgg_extract('x2', $params, 0); $y2 = (int) elgg_extract('y2', $params, 0); if ($x2 > $x1 && $y2 > $y1) { $crop_start = new Point($x1, $y1); $crop_size = new Box($x2 - $x1, $y2 - $y1); $image->crop($crop_start, $crop_size); } $target_size = new Box($max_width, $max_height); $thumbnail = $image->resize($target_size); $thumbnail->save($destination, ['jpeg_quality' => elgg_extract('jpeg_quality', $params, self::JPEG_QUALITY)]); unset($image); unset($thumbnail); } catch (Exception $ex) { _elgg_services()->logger->error($ex->getMessage()); return false; } return true; }
/** * Execute the job. * * @param \Imagine\Image\ImagineInterface $imagine * * @return void */ public function handle(ImagineInterface $imagine) { $data = $this->getFilteredOptions($this->options); $path = $data['path']; $source = Str::replace('{filename}.{extension}', $data); $destination = Str::replace($data['format'], $data); $this->handleImageManipulation($imagine->open("{$path}/{$source}"), $data)->save("{$path}/{$destination}"); }
/** * {@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())); }
/** * @param ThumbId $thumbId * @param Photo $photo * @param PhotoThumbSize $thumbSize * @param HttpUrl $thumbHttpUrl * @return PhotoThumb */ public function generate(ThumbId $thumbId, Photo $photo, PhotoThumbSize $thumbSize, HttpUrl $thumbHttpUrl) { $photoFile = $photo->photoFile() ? $photo->photoFile() : $this->downloadPhoto($photo->getPhotoHttpUrl()); $thumbFile = $this->thumbGeneratorConfig->tempPath() . '/' . $thumbId->id() . '.' . self::CONVERSION_FORMAT; $target = new Box($thumbSize->width(), $thumbSize->height()); $originalImage = $this->imagine->open($photoFile->filePath()); $img = $originalImage->thumbnail($target, ImageInterface::THUMBNAIL_OUTBOUND); $img->save($thumbFile); return new PhotoThumb($thumbId, new PhotoId($photo->id()), $thumbHttpUrl, $thumbSize, new PhotoFile($thumbFile)); }
/** * {@inheritdoc} */ public function load(ImageInterface $image, array $options = array()) { $background = $image->palette()->color(isset($options['color']) ? $options['color'] : '#fff', isset($options['transparency']) ? $options['transparency'] : null); $topLeft = new Point(0, 0); $size = $image->getSize(); if (isset($options['size'])) { list($width, $height) = $options['size']; $position = isset($options['position']) ? $options['position'] : 'center'; switch ($position) { case 'topleft': $x = 0; $y = 0; break; case 'top': $x = ($width - $image->getSize()->getWidth()) / 2; $y = 0; break; case 'topright': $x = $width - $image->getSize()->getWidth(); $y = 0; break; case 'left': $x = 0; $y = ($height - $image->getSize()->getHeight()) / 2; break; case 'center': $x = ($width - $image->getSize()->getWidth()) / 2; $y = ($height - $image->getSize()->getHeight()) / 2; break; case 'right': $x = $width - $image->getSize()->getWidth(); $y = ($height - $image->getSize()->getHeight()) / 2; break; case 'bottomleft': $x = 0; $y = $height - $image->getSize()->getHeight(); break; case 'bottom': $x = ($width - $image->getSize()->getWidth()) / 2; $y = $height - $image->getSize()->getHeight(); break; case 'bottomright': $x = $width - $image->getSize()->getWidth(); $y = $height - $image->getSize()->getHeight(); break; default: throw new \InvalidArgumentException("Unexpected position '{$position}'"); break; } $size = new Box($width, $height); $topLeft = new Point($x, $y); } $canvas = $this->imagine->create($size, $background); return $canvas->paste($image, $topLeft); }
/** * {@inheritDoc} */ function load(array $options = array()) { if (false == isset($options['image'])) { throw new \InvalidArgumentException('Option "image" is required.'); } if (false == is_readable($options['image'])) { throw new \InvalidArgumentException('Expected image file exists and readable.'); } $x = isset($options['x']) ? $options['x'] : 0; $y = isset($options['y']) ? $options['y'] : 0; $image = $this->imagine->open($options['image']); return new PasteFilter($image, $x, $y); }
/** * {@inheritdoc} */ public function load(ImageInterface $image, array $options = array()) { $background = new Color(isset($options['color']) ? $options['color'] : '#fff', isset($options['transparency']) ? $options['transparency'] : 0); $topLeft = new Point(0, 0); $size = $image->getSize(); if (isset($options['size'])) { list($width, $height) = $options['size']; $size = new Box($width, $height); $topLeft = new Point(($width - $image->getSize()->getWidth()) / 2, ($height - $image->getSize()->getHeight()) / 2); } $canvas = $this->imagine->create($size, $background); return $canvas->paste($image, $topLeft); }
/** * {@inheritdoc} */ public function generate($toFile = null) { $fontSize = max(min($this->dimension->getWidth() / strlen($this->text) * 1.15, $this->dimension->getHeight() * 0.5), 5); $palette = new RGB(); $image = $this->imagine->create(new Box($this->dimension->getWidth(), $this->dimension->getHeight()), $palette->color($this->backgroundColor->getColor())); $font = ImagineFactory::createFontInstance($this->instanceType, __DIR__ . '/resource/mplus.ttf', $fontSize, $palette->color($this->stringColor->getColor())); $textProperties = $font->box($this->text); $image->draw()->text($this->text, $font, new Point(($this->dimension->getWidth() - $textProperties->getWidth()) / 2, ($this->dimension->getHeight() - $textProperties->getHeight()) / 2)); if ($toFile !== null) { $image->save($toFile); } return new Result($image, $toFile); }
/** * Sets ImageRenderer as Renderer when ImageModel is used * * @param ViewEvent $e * @return ImageRenderer|null * @throws Exception\RuntimeException */ public function selectRenderer(ViewEvent $e) { $model = $e->getModel(); if ($model instanceof ImageModel) { if (!$model->getImage() instanceof ImageInterface) { if (!$model->getImagePath()) { throw new Exception\RuntimeException('You must provide Imagine\\Image\\ImageInterface or path of image'); } $model->setImage($this->imagine->open($model->getImagePath())); } return new ImageRenderer(); } }
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; }
/** * {@inheritDoc} */ public function apply(ImageInterface $image) { if ($this->size) { list($width, $height) = $this->size; $size = new Box($width, $height); $topLeft = new Point(($width - $image->getSize()->getWidth()) / 2, ($height - $image->getSize()->getHeight()) / 2); } else { $topLeft = new Point(0, 0); $size = $image->getSize(); } $background = $image->palette()->color($this->color); $canvas = $this->imagine->create($size, $background); return $canvas->paste($image, $topLeft); }
/** * {@inheritDoc} */ public function load(array $options = []) { if (!isset($options['image'])) { throw new Exception\InvalidArgumentException('Option "image" is required.'); } $x = isset($options['x']) ? $options['x'] : 0; $y = isset($options['y']) ? $options['y'] : 0; $path = $this->resolver->resolve($options['image']); if (!$path) { throw new Exception\RuntimeException(sprintf('Could not resolve %s', $options['image'])); } $image = $this->imagine->open($path); return new PasteFilter($image, $x, $y); }
/** * Forces image caching and returns path to cached image. * * @param string $basePath Deprecated parameter * @param string $path * @param string $filter * @param boolean $force * @param string $saveAs * * @return string|null * * @throws RuntimeException */ public function cacheImage($basePath, $path, $filter, $force = false, $saveAs = null) { $path = '/' . ltrim($path, '/'); $saveAs = $saveAs ? '/' . ltrim($saveAs, '/') : $path; // if cache path cannot be determined, return 404 if (!($cachedPath = $this->cachePathResolver->getCachedPath($saveAs, $filter))) { return null; } // if the file has already been cached, just return path if (!$force && is_file($cachedPath)) { return $cachedPath; } if (!($sourcePath = $this->cachePathResolver->getRealPath($path, $filter))) { return null; } $this->ensureDirectoryExists($cachedPath); try { $image = $this->imagine->open($sourcePath); } catch (RuntimeException $e) { try { // Make sure source path is an image new ImageFile($sourcePath, false); // Do not pollute the space (don't copy anything; symlink is just fine) $this->filesystem->symlink($sourcePath, $cachedPath); } catch (RuntimeException $e) { return null; } catch (IOException $e) { // In case we were not able to create symlink we should return source path. // This means we'll be back here, but at least we'll not be polluting space with useless copies. return $sourcePath; } return $cachedPath; } $options = ['quality' => $this->filterManager->getOption($filter, 'quality', $this->defaultQuality), 'format' => $this->filterManager->getOption($filter, 'format', null)]; // Important! optipng filter returns an instance of ImageAssetWrapper. /** @var ImageInterface|ImageAssetWrapper $image */ $image = $this->filterManager->getFilter($filter)->apply($image); /** @var resource $context */ if ($context = $this->findStreamContext($cachedPath, $filter)) { $tmpPath = tempnam(sys_get_temp_dir(), 'avalanche-cache-manager-proxy-'); $image->save($tmpPath, $options); copy($tmpPath, $cachedPath, $context); unlink($tmpPath); } else { $image->save($cachedPath, $options); } $this->ensureFilePermissions($cachedPath); return $cachedPath; }
public function apply(ImageInterface &$image, ImagineInterface $imagine) { $box = $image->getSize(); // x and y is the center of the crop $x = Helper::percentValue($this->_x, $boxw = $box->getWidth()); $y = Helper::percentValue($this->_y, $boxh = $box->getHeight()); $w = Helper::percentValue($this->_width, $boxw); $h = Helper::percentValue($this->_height, $boxh); if ($this->_ratio) { switch ($this->_ratio) { case self::COVER: Helper::scaleSize($w, $h, $box); $w = $h = min($w, $h); break; case self::CONTAIN: Helper::scaleSize($w, $h, $box); $max = max($w, $h); $img = $imagine->create(new Box($max, $max), new Color(0, 100)); $img->paste($image, new Point(($max - $boxw) * 0.5, ($max - $boxh) * 0.5)); $image = $img; return; default: // custom ratio $this->fitByRatio($w, $h, $w && $h ? $w / $h : 0); if (!$w || !$h) { throw new \RuntimeException('Invalid ratio supplied'); } break; } } else { Helper::scaleSize($w, $h, $box); } $halfw = $w / 2; $halfh = $h / 2; if ($x + $halfw > $boxw) { $x = $boxw - $halfw; } if ($y + $halfh > $boxh) { $y = $boxh - $halfh; } if ($x < $halfw) { $x = $halfw; } if ($y < $halfh) { $y = $halfh; } $image->crop(new Point($x - $w / 2, $y - $h / 2), new Box($w, $h)); }
/** * Resize an image using the computed settings. * * @param FileInterface $file * @param Style $style * @return string */ public function resize(FileInterface $file, Style $style) { $filePath = tempnam(sys_get_temp_dir(), 'STP') . '.' . $file->getFilename(); list($width, $height, $option) = $this->parseStyleDimensions($style); $method = "resize" . ucfirst($option); if ($method == 'resizeCustom') { $this->resizeCustom($file, $style->dimensions)->save($filePath, $style->convertOptions); return $filePath; } $image = $this->imagine->open($file->getRealPath()); if ($style->autoOrient) { $image = $this->autoOrient($file->getRealPath(), $image); } $this->{$method}($image, $width, $height)->save($filePath, $style->convertOptions); return $filePath; }
/** * {@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)); }
private function convertSvgToImage($content) { $temporaryFilePath = $this->createTemporaryFile($content); $image = $this->imagine->open($temporaryFilePath); unlink($temporaryFilePath); return $image->get('png'); }
/** * Process an Image * * @param Image $image * * @return ImagineInterface */ public function process(Image $image) { $processors = $image->getSalts(); $image = $this->imagine->open($image->getOriginalImagePath()); // Apply each method one after the other foreach ($processors as $method => $arguments) { if (empty($arguments) or isset($arguments[0])) { $image = $this->executeMethod($image, $method, $arguments); } else { foreach ($arguments as $submethod => $arguments) { $this->executeSubmethod($image, $method, $submethod, $arguments); } } } return $image; }
/** * Set properties for text drawing on the image. * * @param $fontFile string path to the font file on server * @param $size int font size to use * @param $color string font color to use in hex format * * @return null */ public function setFontProperties($fontFile, $size, $color) { if (empty($this->_palette)) { $this->_palette = new \Imagine\Image\Palette\RGB(); } $this->_font = $this->_instance->font($fontFile, $size, $this->_palette->color($color)); }
/** * {@inheritdoc} */ protected function doTransform(MediaInterface $media) { parent::doTransform($media); if ($media->getBinaryContent() instanceof UploadedFile) { $fileName = $media->getBinaryContent()->getClientOriginalName(); } elseif ($media->getBinaryContent() instanceof File) { $fileName = $media->getBinaryContent()->getFilename(); } else { // Should not happen, FileProvider should throw an exception in that case return; } if (!in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $this->allowedExtensions) || !in_array($media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes)) { return; } try { $image = $this->imagineAdapter->open($media->getBinaryContent()->getPathname()); } catch (\RuntimeException $e) { $media->setProviderStatus(MediaInterface::STATUS_ERROR); return; } $size = $image->getSize(); $media->setWidth($size->getWidth()); $media->setHeight($size->getHeight()); $media->setProviderStatus(MediaInterface::STATUS_OK); }
public function getImagineImage(ImagineInterface $imagine, FontCollection $fontCollection, $width, $height) { $watermarkImage = $imagine->open($this->getPath()); if ($this->getRelativeSize() !== null) { $y = (int) $height * $this->getRelativeSize() / 100; $factor = $y / $watermarkImage->getSize()->getHeight(); $x = $watermarkImage->getSize()->getWidth() * $factor; $actualWidth = $width - abs($this->positionX); if ($x > $actualWidth) { $factor = $actualWidth / $x; $x = $actualWidth; $y *= $factor; } $watermarkImage->resize(new \Imagine\Image\Box($x, $y)); } return $watermarkImage; }
/** * @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()); }
/** * 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 } }