本文整理汇总了PHP中Imagine\Image\ImagineInterface::open方法的典型用法代码示例。如果您正苦于以下问题:PHP ImagineInterface::open方法的具体用法?PHP ImagineInterface::open怎么用?PHP ImagineInterface::open使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Imagine\Image\ImagineInterface
的用法示例。
在下文中一共展示了ImagineInterface::open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: resize
/**
* 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;
}
示例2: getImage
/**
* {@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];
}
示例3: process
/**
* @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;
}
示例4: find
/**
* {@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);
}
示例5: generate
/**
* @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));
}
示例6: selectRenderer
/**
* 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();
}
}
示例7: load
/**
* {@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);
}
示例8: load
/**
* {@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);
}
示例9: cacheImage
/**
* 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;
}
示例10: resize
/**
* 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;
}
示例11: process
/**
* 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;
}
示例12: doTransform
/**
* {@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);
}
示例13: convertSvgToImage
private function convertSvgToImage($content)
{
$temporaryFilePath = $this->createTemporaryFile($content);
$image = $this->imagine->open($temporaryFilePath);
unlink($temporaryFilePath);
return $image->get('png');
}
示例14: generate
/**
* Generate Badge images
*
* @param Bundle $bundle
*/
public function generate(Bundle $bundle)
{
// Open bg badge image
$image = $this->imagine->open($this->getResourceDir() . '/images/' . $this->type[self::LONG]);
$imageShort = $this->imagine->open($this->getResourceDir() . '/images/' . $this->type[self::SHORT]);
// Bundle Title
$bundleName = $this->shorten($bundle->getName(), 16);
$image->draw()->text($bundleName, $this->setFont($this->imagine, $this->font, 14, '085066'), new Point(75, 10));
// Score points
$score = $bundle->getScore() ?: 'N/A';
$image->draw()->text($score, $this->setFont($this->imagine, $this->font, 18), $this->getPositionByType($score, self::LONG));
$imageShort->draw()->text($score, $this->setFont($this->imagine, $this->font, 16), $this->getPositionByType($score, self::SHORT));
// Recommend
$recommenders = $bundle->getNbRecommenders();
if ($recommenders) {
$recommendationsText = $recommenders . ' recommendations';
} else {
$recommendationsText = 'No recommendations';
}
$image->draw()->text($recommendationsText, $this->setFont($this->imagine, $this->font, 9), new Point(92, 33));
// Check or create dir for generated badges
$this->createBadgesDir();
// Remove existing badge
$this->filesystem->remove($this->getBadgeFile($bundle));
$this->filesystem->remove($this->getBadgeFile($bundle, self::SHORT));
// Save badge
$image->save($this->getBadgeFile($bundle));
$imageShort->save($this->getBadgeFile($bundle, self::SHORT));
// Set write permission for father files update
chmod($this->getBadgeFile($bundle), 0777);
chmod($this->getBadgeFile($bundle, self::SHORT), 0777);
}
示例15: processImage
/**
* @param FlowResource $originalResource
* @param array $adjustments
* @return array resource, width, height as keys
* @throws ImageFileException
* @throws InvalidConfigurationException
* @throws \TYPO3\Flow\Resource\Exception
*/
public function processImage(FlowResource $originalResource, array $adjustments)
{
$additionalOptions = array();
$adjustmentsApplied = false;
// TODO: Special handling for SVG should be refactored at a later point.
if ($originalResource->getMediaType() === 'image/svg+xml') {
$originalResourceStream = $originalResource->getStream();
$resource = $this->resourceManager->importResource($originalResourceStream, $originalResource->getCollectionName());
fclose($originalResourceStream);
$resource->setFilename($originalResource->getFilename());
return ['width' => null, 'height' => null, 'resource' => $resource];
}
$resourceUri = $originalResource->createTemporaryLocalCopy();
$resultingFileExtension = $originalResource->getFileExtension();
$transformedImageTemporaryPathAndFilename = $this->environment->getPathToTemporaryDirectory() . uniqid('ProcessedImage-') . '.' . $resultingFileExtension;
if (!file_exists($resourceUri)) {
throw new ImageFileException(sprintf('An error occurred while transforming an image: the resource data of the original image does not exist (%s, %s).', $originalResource->getSha1(), $resourceUri), 1374848224);
}
$imagineImage = $this->imagineService->open($resourceUri);
if ($this->imagineService instanceof \Imagine\Imagick\Imagine && $originalResource->getFileExtension() === 'gif' && $this->isAnimatedGif(file_get_contents($resourceUri)) === true) {
$imagineImage->layers()->coalesce();
$layers = $imagineImage->layers();
$newLayers = array();
foreach ($layers as $index => $imagineFrame) {
$imagineFrame = $this->applyAdjustments($imagineFrame, $adjustments, $adjustmentsApplied);
$newLayers[] = $imagineFrame;
}
$imagineImage = array_shift($newLayers);
$layers = $imagineImage->layers();
foreach ($newLayers as $imagineFrame) {
$layers->add($imagineFrame);
}
$additionalOptions['animated'] = true;
} else {
$imagineImage = $this->applyAdjustments($imagineImage, $adjustments, $adjustmentsApplied);
}
if ($adjustmentsApplied === true) {
$imagineImage->save($transformedImageTemporaryPathAndFilename, $this->getOptionsMergedWithDefaults($additionalOptions));
$imageSize = $imagineImage->getSize();
// TODO: In the future the collectionName of the new resource should be configurable.
$resource = $this->resourceManager->importResource($transformedImageTemporaryPathAndFilename, $originalResource->getCollectionName());
if ($resource === false) {
throw new ImageFileException('An error occurred while importing a generated image file as a resource.', 1413562208);
}
unlink($transformedImageTemporaryPathAndFilename);
$pathInfo = UnicodeFunctions::pathinfo($originalResource->getFilename());
$resource->setFilename(sprintf('%s-%ux%u.%s', $pathInfo['filename'], $imageSize->getWidth(), $imageSize->getHeight(), $pathInfo['extension']));
} else {
$originalResourceStream = $originalResource->getStream();
$resource = $this->resourceManager->importResource($originalResourceStream, $originalResource->getCollectionName());
fclose($originalResourceStream);
$resource->setFilename($originalResource->getFilename());
$imageSize = $this->getImageSize($originalResource);
$imageSize = new Box($imageSize['width'], $imageSize['height']);
}
$this->imageSizeCache->set($resource->getCacheEntryIdentifier(), array('width' => $imageSize->getWidth(), 'height' => $imageSize->getHeight()));
$result = array('width' => $imageSize->getWidth(), 'height' => $imageSize->getHeight(), 'resource' => $resource);
return $result;
}