Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use Error;
use Imagick;
use Intervention\Image\Analyzers\ColorspaceAnalyzer as GenericColorspaceAnalyzer;
use Intervention\Image\Colors\Cmyk\Colorspace as Cmyk;
use Intervention\Image\Colors\Hsl\Colorspace as Hsl;
use Intervention\Image\Colors\Hsv\Colorspace as Hsv;
use Intervention\Image\Colors\Oklab\Colorspace as Oklab;
use Intervention\Image\Colors\Oklch\Colorspace as Oklch;
use Intervention\Image\Colors\Rgb\Colorspace as Rgb;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class ColorspaceAnalyzer extends GenericColorspaceAnalyzer implements SpecializedInterface
{
/**
* @throws AnalyzerException
*/
public function analyze(ImageInterface $image): mixed
{
try {
$colorspace = $image->core()->native()->getImageColorspace();
// OKLAB/OKLCH only exist on recent ImageMagick builds, so the
// constants are resolved through defined()/constant() (mirroring the
// ColorspaceModifier) to avoid referencing them where they are
// undefined. Any unexpected resolution error is normalized below.
return match (true) {
$colorspace === Imagick::COLORSPACE_CMYK => new Cmyk(),
$colorspace === Imagick::COLORSPACE_SRGB,
$colorspace === Imagick::COLORSPACE_RGB => new Rgb(),
$colorspace === Imagick::COLORSPACE_HSL => new Hsl(),
$colorspace === Imagick::COLORSPACE_HSB => new Hsv(),
defined(Imagick::class . '::COLORSPACE_OKLAB')
&& $colorspace === constant(Imagick::class . '::COLORSPACE_OKLAB') => new Oklab(),
defined(Imagick::class . '::COLORSPACE_OKLCH')
&& $colorspace === constant(Imagick::class . '::COLORSPACE_OKLCH') => new Oklch(),
default => throw new AnalyzerException('Failed to analyze unknown colorspace'),
};
} catch (Error $e) {
throw new AnalyzerException('Failed to analyze colorspace', previous: $e);
}
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use ImagickException;
use Intervention\Image\Analyzers\HeightAnalyzer as GenericHeightAnalyzer;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class HeightAnalyzer extends GenericHeightAnalyzer implements SpecializedInterface
{
/**
* @throws AnalyzerException
*/
public function analyze(ImageInterface $image): mixed
{
try {
return $image->core()->native()->getImageHeight();
} catch (ImagickException $e) {
throw new AnalyzerException('Failed to read image height', previous: $e);
}
}
}

View file

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use ImagickException;
use Intervention\Image\Analyzers\PixelColorAnalyzer as GenericPixelColorAnalyzer;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ColorInterface;
use Intervention\Image\Interfaces\ColorProcessorInterface;
use Intervention\Image\Interfaces\FrameInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class PixelColorAnalyzer extends GenericPixelColorAnalyzer implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws AnalyzerException
* @throws StateException
*/
public function analyze(ImageInterface $image): mixed
{
if ($this->x > $image->width() - 1 || $this->y > $image->height() - 1) {
throw new InvalidArgumentException(
'The specified position (' . $this->x . ', ' . $this->y . ') is not within the image area',
);
}
$colorProcessor = $this->driver()->colorProcessor($image);
return $this->colorAt($colorProcessor, $image->core()->frame($this->frame));
}
/**
* @throws AnalyzerException
*/
protected function colorAt(ColorProcessorInterface $processor, FrameInterface $frame): ColorInterface
{
try {
return $processor->import(
$frame->native()->getImagePixelColor($this->x, $this->y),
);
} catch (ImagickException $e) {
throw new AnalyzerException(
'Failed to read pixel color at position ' . $this->x . ', ' . $this->y,
previous: $e,
);
}
}
}

View file

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use Intervention\Image\Collection;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
class PixelColorsAnalyzer extends PixelColorAnalyzer
{
/**
* @throws AnalyzerException
* @throws StateException
*/
public function analyze(ImageInterface $image): mixed
{
$colors = new Collection();
$colorProcessor = $this->driver()->colorProcessor($image);
foreach ($image as $frame) {
$colors->push(
parent::colorAt($colorProcessor, $frame),
);
}
return $colors;
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use Intervention\Image\Analyzers\ProfileAnalyzer as GenericProfileAnalyzer;
use Intervention\Image\Colors\Profile;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class ProfileAnalyzer extends GenericProfileAnalyzer implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws AnalyzerException
*/
public function analyze(ImageInterface $image): mixed
{
$profiles = $image->core()->native()->getImageProfiles('icc');
if (!array_key_exists('icc', $profiles)) {
throw new AnalyzerException('No ICC profile found in image');
}
return new Profile($profiles['icc']);
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use ImagickException;
use Intervention\Image\Analyzers\ResolutionAnalyzer as GenericResolutionAnalyzer;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Length;
use Intervention\Image\Resolution;
class ResolutionAnalyzer extends GenericResolutionAnalyzer implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws AnalyzerException
*/
public function analyze(ImageInterface $image): mixed
{
$imagick = $image->core()->native();
try {
$imageResolution = $imagick->getImageResolution();
} catch (ImagickException $e) {
throw new AnalyzerException('Failed to read image resolution', previous: $e);
}
return new Resolution(
$imageResolution['x'],
$imageResolution['y'],
$imagick->getImageUnits() === 2 ? Length::CM : Length::INCH,
);
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Analyzers;
use ImagickException;
use Intervention\Image\Analyzers\WidthAnalyzer as GenericWidthAnalyzer;
use Intervention\Image\Exceptions\AnalyzerException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class WidthAnalyzer extends GenericWidthAnalyzer implements SpecializedInterface
{
/**
* @throws AnalyzerException
*/
public function analyze(ImageInterface $image): mixed
{
try {
return $image->core()->native()->getImageWidth();
} catch (ImagickException $e) {
throw new AnalyzerException('Failed to read image width', previous: $e);
}
}
}

View file

@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick;
use Imagick;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Colors\Cmyk\Channels\Cyan;
use Intervention\Image\Colors\Cmyk\Channels\Key;
use Intervention\Image\Colors\Cmyk\Channels\Magenta;
use Intervention\Image\Colors\Cmyk\Channels\Yellow;
use Intervention\Image\Colors\Cmyk\Colorspace as Cmyk;
use Intervention\Image\Colors\Hsl\Colorspace as Hsl;
use Intervention\Image\Colors\Hsv\Colorspace as Hsv;
use Intervention\Image\Colors\Oklab\Colorspace as Oklab;
use Intervention\Image\Colors\Oklch\Colorspace as Oklch;
use Intervention\Image\Colors\Rgb\Channels\Alpha;
use Intervention\Image\Colors\Rgb\Channels\Blue;
use Intervention\Image\Colors\Rgb\Channels\Green;
use Intervention\Image\Colors\Rgb\Channels\Red;
use Intervention\Image\Colors\Rgb\Colorspace as Rgb;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Interfaces\ColorInterface;
use Intervention\Image\Interfaces\ColorProcessorInterface;
use Intervention\Image\Interfaces\ColorspaceInterface;
class ColorProcessor implements ColorProcessorInterface
{
/**
* Create new instance.
*/
public function __construct(protected ColorspaceInterface $colorspace)
{
//
}
/**
* {@inheritdoc}
*
* @see ColorProcessorInterface::colorspace()
*/
public function colorspace(): ColorspaceInterface
{
return $this->colorspace;
}
/**
* @throws DriverException
*/
public function export(ColorInterface $color): ImagickPixel
{
$color = $this->colorspace->importColor($color);
if ($this->colorspace instanceof Cmyk) {
try {
$pixel = new ImagickPixel();
$pixel->setColorValue(Imagick::COLOR_CYAN, $color->channel(Cyan::class)->normalized());
$pixel->setColorValue(Imagick::COLOR_MAGENTA, $color->channel(Magenta::class)->normalized());
$pixel->setColorValue(Imagick::COLOR_YELLOW, $color->channel(Yellow::class)->normalized());
$pixel->setColorValue(Imagick::COLOR_BLACK, $color->channel(Key::class)->normalized());
} catch (ImagickException | ImagickPixelException $e) {
throw new DriverException('Failed to create CMYK color', previous: $e);
}
return $pixel;
}
$color = $color->toColorspace(Rgb::class);
try {
return new ImagickPixel(
sprintf(
"srgba(%s, %s, %s, %s)",
$color->channel(Red::class)->value(),
$color->channel(Green::class)->value(),
$color->channel(Blue::class)->value(),
$color->channel(Alpha::class)->toString(),
),
);
} catch (ImagickException | ImagickPixelException $e) {
throw new DriverException('Failed to create color', previous: $e);
}
}
/**
* @throws InvalidArgumentException
* @throws DriverException
* @throws NotSupportedException
*/
public function import(mixed $color): ColorInterface
{
if (!$color instanceof ImagickPixel) {
throw new InvalidArgumentException(
'Imagick driver can only process colors from instances of ' . ImagickPixel::class,
);
}
try {
return match ($this->colorspace::class) {
Cmyk::class => $this->colorspace->colorFromNormalized([
$color->getColorValue(Imagick::COLOR_CYAN),
$color->getColorValue(Imagick::COLOR_MAGENTA),
$color->getColorValue(Imagick::COLOR_YELLOW),
$color->getColorValue(Imagick::COLOR_BLACK),
]),
Rgb::class => $this->colorspace->colorFromNormalized([
$color->getColorValue(Imagick::COLOR_RED),
$color->getColorValue(Imagick::COLOR_GREEN),
$color->getColorValue(Imagick::COLOR_BLUE),
$color->getColorValue(Imagick::COLOR_ALPHA),
]),
Hsl::class => Rgb::class::colorFromNormalized([
$color->getColorValue(Imagick::COLOR_RED),
$color->getColorValue(Imagick::COLOR_GREEN),
$color->getColorValue(Imagick::COLOR_BLUE),
$color->getColorValue(Imagick::COLOR_ALPHA),
])->toColorspace(Hsl::class),
Hsv::class => Rgb::colorFromNormalized([
$color->getColorValue(Imagick::COLOR_RED),
$color->getColorValue(Imagick::COLOR_GREEN),
$color->getColorValue(Imagick::COLOR_BLUE),
$color->getColorValue(Imagick::COLOR_ALPHA),
])->toColorspace(Hsv::class),
Oklab::class => Rgb::colorFromNormalized([
$color->getColorValue(Imagick::COLOR_RED),
$color->getColorValue(Imagick::COLOR_GREEN),
$color->getColorValue(Imagick::COLOR_BLUE),
$color->getColorValue(Imagick::COLOR_ALPHA),
])->toColorspace(Oklab::class),
Oklch::class => Rgb::colorFromNormalized([
$color->getColorValue(Imagick::COLOR_RED),
$color->getColorValue(Imagick::COLOR_GREEN),
$color->getColorValue(Imagick::COLOR_BLUE),
$color->getColorValue(Imagick::COLOR_ALPHA),
])->toColorspace(Oklch::class),
default => throw new NotSupportedException(
'Colorspace ' . $this->colorspace::class . ' is not supported by driver',
)
};
} catch (ImagickPixelException $e) {
throw new DriverException(
'Failed to import color from ' . ImagickPixel::class,
previous: $e,
);
}
}
}

View file

@ -0,0 +1,450 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick;
use Exception;
use Imagick;
use ImagickException;
use Intervention\Image\Collection;
use Intervention\Image\Exceptions\DriverException;
use Iterator;
use Intervention\Image\Interfaces\CoreInterface;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\CollectionInterface;
use Intervention\Image\Interfaces\FrameInterface;
/**
* @implements Iterator<FrameInterface>
*/
class Core implements CoreInterface, Iterator
{
protected int $iteratorIndex = 0;
protected CollectionInterface $meta;
/**
* Create new core instance
*/
public function __construct(protected Imagick $imagick)
{
$this->meta = new Collection();
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::has()
*/
public function has(int|string $key): bool
{
try {
return $this->imagick->setIteratorIndex((int) $key);
} catch (ImagickException) {
return false;
}
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::push()
*
* @throws DriverException
*/
public function push(mixed $item): CollectionInterface
{
return $this->add($item);
}
/**
* {@inheritdoc}
*
* @see CoreInterface::map()
*
* @throws NotSupportedException
*/
public function map(callable $callback): CoreInterface
{
throw new NotSupportedException('Not implemented');
}
/**
* {@inheritdoc}
*
* @see CoreInterface::filter()
*
* @throws Exception
*/
public function filter(callable $callback): CoreInterface
{
throw new \Exception('Not implemented');
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::get()
*
* @throws DriverException
*/
public function get(int|string $key, mixed $default = null): mixed
{
try {
$this->imagick->setIteratorIndex((int) $key);
} catch (ImagickException) {
return $default;
}
try {
return new Frame($this->imagick->current());
} catch (ImagickException | RuntimeException $e) {
throw new DriverException('Failed to get current frame data', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::set()
*
* @throws DriverException
*/
public function set(int|string $key, mixed $item): CollectionInterface
{
return $this->add($item);
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::at()
*
* @throws DriverException
*/
public function at(int $key = 0, mixed $default = null): mixed
{
return $this->get($key, $default);
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::clear()
*/
public function clear(): CollectionInterface
{
$this->imagick->clear();
return $this;
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::slice()
*
* @throws DriverException
*/
public function slice(int $offset, ?int $length = null): CollectionInterface
{
$length = is_null($length) ? $this->count() : $length;
$count = $this->count();
for ($i = $count - 1; $i >= 0; $i--) {
if ($i < $offset || $i >= $offset + $length) {
try {
$this->imagick->setIteratorIndex($i);
$this->imagick->removeImage();
} catch (ImagickException $e) {
throw new DriverException('Failed to slice image', previous: $e);
}
}
}
try {
$loops = $this->imagick->getImageIterations();
$coalesced = $this->imagick->coalesceImages();
$this->imagick->clear();
$this->imagick = $coalesced;
$this->imagick->setImageIterations($loops);
} catch (ImagickException $e) {
throw new DriverException('Failed to slice image', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see CoreInterface::add()
*
* @throws DriverException
*/
public function add(FrameInterface $frame): CoreInterface
{
$imagick = $frame->native();
try {
$imagick->setImageDelay(
(int) round($frame->delay() * 100),
);
$imagick->setImageDispose($frame->disposalMethod());
$size = $frame->size();
$imagick->setImagePage(
$size->width(),
$size->height(),
$frame->offsetLeft(),
$frame->offsetTop(),
);
$this->imagick->addImage($imagick);
} catch (ImagickException $e) {
throw new DriverException('Failed to add image frame', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see CoreInterface::count()
*
* @throws DriverException
*/
public function count(): int
{
try {
return $this->imagick->getNumberImages();
} catch (ImagickException $e) {
throw new DriverException('Failed to count image frames', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see Iterator::rewind()
*
* @throws DriverException
*/
public function current(): mixed
{
try {
$this->imagick->setIteratorIndex($this->iteratorIndex);
return new Frame($this->imagick->current());
} catch (ImagickException | RuntimeException $e) {
throw new DriverException('Failed to iterate image frames', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see Iterator::rewind()
*/
public function next(): void
{
$this->iteratorIndex += 1;
}
/**
* {@inheritdoc}
*
* @see Iterator::rewind()
*/
public function key(): mixed
{
return $this->iteratorIndex;
}
/**
* {@inheritdoc}
*
* @see Iterator::rewind()
*/
public function valid(): bool
{
try {
$result = $this->imagick->setIteratorIndex($this->iteratorIndex);
} catch (ImagickException) {
return false;
}
return $result;
}
/**
* {@inheritdoc}
*
* @see Iterator::rewind()
*/
public function rewind(): void
{
$this->iteratorIndex = 0;
}
/**
* {@inheritdoc}
*
* @see CoreInterface::native()
*/
public function native(): mixed
{
return $this->imagick;
}
/**
* {@inheritdoc}
*
* @see CoreInterface::setNative()
*
* @throws InvalidArgumentException
*/
public function setNative(mixed $native): CoreInterface
{
if (!$native instanceof Imagick) {
throw new InvalidArgumentException('Argument $native must be of type ' . Imagick::class);
}
$this->imagick->clear();
$this->imagick = $native;
return $this;
}
/**
* {@inheritdoc}
*
* @see CoreInterface::frame()
*
* @throws InvalidArgumentException
* @throws DriverException
*/
public function frame(int $position): FrameInterface
{
foreach ($this->imagick as $core) {
try {
if ($core->getIteratorIndex() === $position) {
return new Frame($core);
}
} catch (ImagickException | RuntimeException $e) {
throw new DriverException('Failed to load image frame a position ' . $position, previous: $e);
}
}
throw new InvalidArgumentException('Frame #' . $position . ' could not be found in the image');
}
/**
* {@inheritdoc}
*
* @see CoreInterface::loops()
*
* @throws DriverException
*/
public function loops(): int
{
try {
return $this->imagick->getImageIterations();
} catch (ImagickException $e) {
throw new DriverException('Failed to get image loop count', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see CoreInterface::setLoops()
*
* @throws DriverException
*/
public function setLoops(int $loops): CoreInterface
{
try {
$this->imagick->resetIterator();
$this->imagick->setImageIterations($loops);
} catch (ImagickException $e) {
throw new DriverException('Failed to set image loop count', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::first()
*
* @throws DriverException
* @throws StateException
*/
public function first(): FrameInterface
{
try {
return $this->frame(0);
} catch (InvalidArgumentException $e) {
throw new StateException('First frame not found in image', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see CollectableInterface::last()
*
* @throws DriverException
* @throws StateException
*/
public function last(): FrameInterface
{
try {
return $this->frame($this->count() - 1);
} catch (InvalidArgumentException $e) {
throw new StateException('Last frame not found in image', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see CoreInterface::meta()
*/
public function meta(): CollectionInterface
{
return $this->meta;
}
/**
* {@inheritdoc}
*
* @see CollectionInterface::toArray()
*/
public function toArray(): array
{
$frames = [];
foreach ($this as $frame) {
$frames[] = $frame;
}
return $frames;
}
/**
* Clone instance
*/
public function __clone(): void
{
$this->meta = clone $this->meta;
$this->imagick = clone $this->imagick;
}
}

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Traits\CanDetectImageSources;
class Base64ImageDecoder extends BinaryImageDecoder
{
use CanDetectImageSources;
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $this->couldBeBase64Data($input);
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*/
public function decode(mixed $input): ImageInterface
{
try {
$data = $this->decodeBase64Data($input);
} catch (DecoderException) {
throw new ImageDecoderException('Unable to Base64-decode image from string');
}
try {
return parent::decode($data);
} catch (DecoderException) {
throw new ImageDecoderException('Base64-encoded data contains unsupported image type');
}
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Format;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Traits\CanDetectImageSources;
use Stringable;
class BinaryImageDecoder extends NativeObjectDecoder
{
use CanDetectImageSources;
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $this->couldBeBinaryData($input);
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws ImageDecoderException
* @throws DriverException
* @throws StateException
*/
public function decode(mixed $input): ImageInterface
{
if (!is_string($input) && !$input instanceof Stringable) {
throw new InvalidArgumentException(
'Image source must be binary data of type string or instance of ' . Stringable::class,
);
}
$input = (string) $input;
if ($input === '') {
throw new InvalidArgumentException('Unable to decode binary data from empty string');
}
try {
$imagick = new Imagick();
$imagick->readImageBlob($input);
} catch (ImagickException) {
throw new ImageDecoderException('Failed to decode unsupported image format from binary data');
}
// decode image
$image = parent::decode($imagick);
// get media type enum from string media type
$format = Format::tryCreate($image->origin()->mediaType());
// extract exif data for appropriate formats
if (in_array($format, [Format::JPEG, Format::TIFF])) {
$image->setExif($this->extractExifData($input));
}
return $image;
}
}

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Intervention\Image\DataUri;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Traits\CanDetectImageSources;
class DataUriImageDecoder extends BinaryImageDecoder
{
use CanDetectImageSources;
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $this->couldBeDataUrl($input);
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws ImageDecoderException
* @throws DriverException
* @throws StateException
*/
public function decode(mixed $input): ImageInterface
{
if ($input instanceof DataUri) {
try {
return parent::decode($input->data());
} catch (DecoderException) {
throw new ImageDecoderException('Data Uri contains unsupported image type');
}
}
if (!is_string($input)) {
throw new InvalidArgumentException(
'Image source must be data uri scheme of type string or ' . DataUri::class,
);
}
try {
return parent::decode(DataUri::parse($input)->data());
} catch (DecoderException) {
throw new ImageDecoderException('Data Uri contains unsupported image type');
}
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Intervention\Image\EncodedImage;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\EncodedImageInterface;
class EncodedImageObjectDecoder extends BinaryImageDecoder
{
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $input instanceof EncodedImageInterface;
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws DriverException
* @throws StateException
* @throws ImageDecoderException
*/
public function decode(mixed $input): ImageInterface
{
if (!$input instanceof EncodedImageInterface) {
throw new InvalidArgumentException('Image source must be of type ' . EncodedImage::class);
}
try {
return parent::decode($input->toString());
} catch (DecoderException) {
throw new ImageDecoderException(EncodedImage::class . ' contains unsupported image type');
}
}
}

View file

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\DirectoryNotFoundException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\FileNotFoundException;
use Intervention\Image\Exceptions\FileNotReadableException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Traits\CanDetectImageSources;
class FilePathImageDecoder extends NativeObjectDecoder
{
use CanDetectImageSources;
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $this->couldBeFilePath($input);
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws DirectoryNotFoundException
* @throws FileNotFoundException
* @throws FileNotReadableException
* @throws DriverException
* @throws StateException
* @throws ImageDecoderException
*/
public function decode(mixed $input): ImageInterface
{
// make sure path is valid
$path = self::readableFilePathOrFail($input);
try {
$imagick = new Imagick();
$imagick->readImage($path);
} catch (ImagickException) {
throw new ImageDecoderException(
'Failed to decode image data from file "' . $path . '"',
);
}
try {
$originalFormat = $imagick->getImageFormat();
} catch (ImagickException $e) {
throw new ImageDecoderException('Failed to retrieve image format', previous: $e);
}
// decode image
$image = parent::decode($imagick);
// set file path on origin
$image->origin()->setFilePath($path);
// extract exif data for the appropriate formats
if (in_array($originalFormat, ['JPEG', 'TIFF', 'TIF'])) {
$image->setExif($this->extractExifData($path));
}
return $image;
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Imagick;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Core;
use Intervention\Image\Drivers\SpecializableDecoder;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Image;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\OrientModifier;
use Intervention\Image\Modifiers\RemoveAnimationModifier;
class NativeObjectDecoder extends SpecializableDecoder implements SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $input instanceof Imagick;
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws StateException
* @throws DriverException
* @throws ImageDecoderException
*/
public function decode(mixed $input): ImageInterface
{
if (!$input instanceof Imagick) {
throw new InvalidArgumentException('Image source must be an instance of Imagick');
}
try {
$originalMimeType = $input->getImageMimeType();
} catch (ImagickException $e) {
throw new ImageDecoderException('Failed to retrieve image media type', previous: $e);
}
// For some JPEG formats, the "coalesceImages()" call leads to an image
// completely filled with background color. The logic behind this is
// incomprehensible for me; could be an imagick bug.
try {
if ($input->getImageFormat() !== 'JPEG') {
$input = $input->coalesceImages();
}
} catch (ImagickException $e) {
throw new DriverException('Failed to coalesce image', previous: $e);
}
// turn images with colorspace 'GRAY' into 'SRGB' to avoid working on
// grayscale colorspace images as this results images loosing color
// information when placed into this image.
try {
if ($input->getImageColorspace() === Imagick::COLORSPACE_GRAY) {
$input->setImageColorspace(Imagick::COLORSPACE_SRGB);
}
// AVIF/HEIF store their pixels in a luma/chroma (YCbCr) colorspace.
// Recent ImageMagick normalizes this to sRGB on decode, but older
// releases report the image as YCbCr, which leaves every later color
// operation (colorspace analysis, pixel reads) working on raw
// luma/chroma values. Convert it to sRGB so colors are correct.
if ($input->getImageColorspace() === Imagick::COLORSPACE_YCBCR) {
$input->transformImageColorspace(Imagick::COLORSPACE_SRGB);
}
} catch (ImagickException $e) {
throw new DriverException('Failed to convert image to sRGB', previous: $e);
}
// create image object
$image = new Image($this->driver(), new Core($input));
// If autoOrientation is disabled, automatic image alignment should be prevented.
// Therefore, it is set to "undefined" here. To still be able to correct the
// orientation manually later, we save the original value.
if ($this->driver()->config()->autoOrientation === false) {
try {
$image->core()->meta()->set('originalImageOrientation', $input->getImageOrientation());
$input->setImageOrientation(Imagick::ORIENTATION_UNDEFINED);
} catch (ImagickException $e) {
throw new ImageDecoderException(
'Failed to set adjust image orientation',
previous: $e,
);
}
}
// discard animation depending on config
if (!$this->driver()->config()->decodeAnimation) {
$image->modify(new RemoveAnimationModifier());
}
// adjust image rotation
if ($this->driver()->config()->autoOrientation) {
$image->modify(new OrientModifier());
}
// set media type on origin
$image->origin()->setMediaType($originalMimeType);
return $image;
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Exceptions\DirectoryNotFoundException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\FileNotFoundException;
use Intervention\Image\Exceptions\FileNotReadableException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use SplFileInfo;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Traits\CanParseFilePath;
class SplFileInfoImageDecoder extends FilePathImageDecoder
{
use CanParseFilePath;
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return $input instanceof SplFileInfo;
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws DirectoryNotFoundException
* @throws FileNotFoundException
* @throws FileNotReadableException
* @throws ImageDecoderException
* @throws DriverException
* @throws StateException
*/
public function decode(mixed $input): ImageInterface
{
if (!$input instanceof SplFileInfo) {
throw new InvalidArgumentException('Image source must be of type ' . SplFileInfo::class);
}
try {
return parent::decode(self::filePathFromSplFileInfoOrFail($input));
} catch (DecoderException) {
throw new ImageDecoderException(SplFileInfo::class . ' contains unsupported image type');
}
}
}

View file

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Decoders;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\ImageDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
class StreamImageDecoder extends BinaryImageDecoder
{
/**
* {@inheritdoc}
*
* @see DecoderInterface::supports()
*/
public function supports(mixed $input): bool
{
return is_resource($input);
}
/**
* {@inheritdoc}
*
* @see DecoderInterface::decode()
*
* @throws InvalidArgumentException
* @throws StreamException
* @throws DriverException
* @throws StateException
*/
public function decode(mixed $input): ImageInterface
{
if (!is_resource($input) || !in_array(get_resource_type($input), ['file', 'stream'])) {
throw new InvalidArgumentException('Image source must be a resource of type "file" or "stream"');
}
$contents = '';
$rewind = rewind($input);
if ($rewind === false) {
throw new StreamException('Failed to rewind position of stream');
}
while (!feof($input)) {
$chunk = fread($input, 1024);
if ($chunk === false) {
throw new StreamException('Failed to read image from stream');
}
$contents .= $chunk;
}
try {
return parent::decode($contents);
} catch (DecoderException) {
throw new ImageDecoderException(
'Failed to decode image from stream, could be unsupported image format',
);
}
}
}

View file

@ -0,0 +1,180 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick;
use Imagick;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Drivers\AbstractDriver;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\MissingDependencyException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Format;
use Intervention\Image\FileExtension;
use Intervention\Image\Image;
use Intervention\Image\Interfaces\ColorProcessorInterface;
use Intervention\Image\Interfaces\CoreInterface;
use Intervention\Image\Interfaces\FontProcessorInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\MediaType;
class Driver extends AbstractDriver
{
/**
* {@inheritdoc}
*
* @see DriverInterface::id()
*/
public function id(): string
{
return 'Imagick';
}
/**
* {@inheritdoc}
*
* @see DriverInterface::checkHealth()
*
* @codeCoverageIgnore
*/
public function checkHealth(): void
{
if (!extension_loaded('imagick') || !class_exists('Imagick')) {
throw new MissingDependencyException(
'Imagick PHP extension must be installed to use this driver',
);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::createImage()
*
* @throws InvalidArgumentException
* @throws DriverException
*/
public function createImage(int $width, int $height): ImageInterface
{
if ($width < 1 || $height < 1) {
throw new InvalidArgumentException('Invalid image size. Must be int<1, max>');
}
try {
$background = new ImagickPixel('rgba(255, 255, 255, 0)');
$imagick = new Imagick();
$imagick->newImage($width, $height, $background, 'png');
$this->applyDefaultSettings($imagick);
} catch (ImagickException | ImagickPixelException $e) {
throw new DriverException('Failed to create new image', previous: $e);
}
return new Image($this, new Core($imagick));
}
/**
* {@inheritdoc}
*
* @see DriverInterface::createCore()
*
* @throws DriverException
*/
public function createCore(array $frames): CoreInterface
{
try {
$core = new Core(new Imagick());
} catch (ImagickException $e) {
throw new DriverException('Failed to create new core', previous: $e);
}
foreach ($frames as $frame) {
$core->add($frame);
}
$this->applyDefaultSettings($core->native());
return $core;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::colorProcessor()
*/
public function colorProcessor(ImageInterface $image): ColorProcessorInterface
{
return new ColorProcessor($image->colorspace());
}
/**
* {@inheritdoc}
*
* @see DriverInterface::fontProcessor()
*/
public function fontProcessor(): FontProcessorInterface
{
return new FontProcessor();
}
/**
* {@inheritdoc}
*
* @see DriverInterface::supports()
*/
public function supports(string|Format|FileExtension|MediaType $identifier): bool
{
try {
$format = Format::create($identifier);
} catch (InvalidArgumentException) {
return false;
}
return count(Imagick::queryFormats($format->name)) >= 1;
}
/**
* Return version of ImageMagick library
*
* @throws DriverException
*/
public function version(): string
{
$pattern = '/^ImageMagick (?P<version>(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)' .
'(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?' .
'(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?)/';
if (preg_match($pattern, Imagick::getVersion()['versionString'], $matches) !== 1) {
throw new DriverException('Unable to read ImageMagick version number');
}
return $matches['version'];
}
/**
* Apply default settings for native image object.
*
* @throws DriverException
*/
private function applyDefaultSettings(Imagick $imagick): Imagick
{
try {
$background = new ImagickPixel('rgba(255, 255, 255, 0)');
$imagick->setType(Imagick::IMGTYPE_UNDEFINED);
$imagick->setImageType(Imagick::IMGTYPE_UNDEFINED);
$imagick->setColorspace(Imagick::COLORSPACE_SRGB);
$imagick->setImageResolution(72, 72);
$imagick->setImageUnits(Imagick::RESOLUTION_PIXELSPERINCH);
$imagick->setImageBackgroundColor($background);
$imagick->setImageIterations(0);
return $imagick;
} catch (ImagickException | ImagickPixelException $e) {
throw new DriverException('Failed to apply default image settings', previous: $e);
}
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\AvifEncoder as GenericAvifEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class AvifEncoder extends GenericAvifEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'AVIF';
$compression = Imagick::COMPRESSION_ZIP;
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/avif');
$imagick->clear();
return $result;
} catch (ImagickException | ImageException $e) {
throw new EncoderException('Failed to encode avif format', previous: $e);
}
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\BmpEncoder as GenericBmpEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class BmpEncoder extends GenericBmpEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'BMP';
$compression = Imagick::COMPRESSION_NO;
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/bmp');
$imagick->clear();
return $result;
} catch (ImagickException | ImageException $e) {
throw new EncoderException('Failed to encode bmp format', previous: $e);
}
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\GifEncoder as GenericGifEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class GifEncoder extends GenericGifEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'GIF';
$compression = Imagick::COMPRESSION_LZW;
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
if ($this->interlaced) {
$imagick->setInterlaceScheme(Imagick::INTERLACE_LINE);
}
$result = new EncodedImage($imagick->getImagesBlob(), 'image/gif');
$imagick->clear();
return $result;
} catch (ImagickException | ImageException $e) {
throw new EncoderException('Failed to encode gif format', previous: $e);
}
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\HeicEncoder as GenericHeicEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class HeicEncoder extends GenericHeicEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'HEIC';
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/heic');
$imagick->clear();
return $result;
} catch (ImagickException | ImageException $e) {
throw new EncoderException('Failed to encode heic format', previous: $e);
}
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\IcoEncoder as GenericIcoEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class IcoEncoder extends GenericIcoEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'ICO';
$compression = Imagick::COMPRESSION_NO;
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/x-icon');
$imagick->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode ico format', previous: $e);
}
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\Jpeg2000Encoder as GenericJpeg2000Encoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class Jpeg2000Encoder extends GenericJpeg2000Encoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'JP2';
$compression = Imagick::COMPRESSION_JPEG;
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setImageBackgroundColor('white');
$imagick->setBackgroundColor('white');
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/jp2');
$imagick->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode jp2 format', previous: $e);
}
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\JpegEncoder as GenericJpegEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class JpegEncoder extends GenericJpegEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'JPEG';
$compression = Imagick::COMPRESSION_JPEG;
$backgroundColor = $this->driver()->decodeColor(
$this->driver()->config()->backgroundColor,
);
// resolve background color because jpeg has no transparency
$background = $this->driver()
->colorProcessor($image)
->export($backgroundColor);
// set alpha value to 1 because Imagick renders
// possible full transparent colors as black
$background->setColorValue(Imagick::COLOR_ALPHA, 1);
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setImageBackgroundColor($background);
$imagick->setBackgroundColor($background);
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
if ($this->progressive) {
$imagick->setInterlaceScheme(Imagick::INTERLACE_PLANE);
}
$result = new EncodedImage($imagick->getImagesBlob(), 'image/jpeg');
$imagick->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode jpeg format', previous: $e);
}
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\JxlEncoder as GenericJxlEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
class JxlEncoder extends GenericJxlEncoder implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'JXL';
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/jxl');
$imagick->clear();
return $result;
} catch (ImagickException | ImageException $e) {
throw new EncoderException('Failed to encode jxl format', previous: $e);
}
}
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\PngEncoder as GenericPngEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class PngEncoder extends GenericPngEncoder implements SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see EncoderInterface::encode()
*
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
try {
if ($this->indexed) {
// reduce colors
$output = clone $image;
$output->reduceColors(256);
$output = $output->core()->native();
$output->setFormat('PNG');
$output->setImageFormat('PNG');
} else {
$output = clone $image->core()->native();
$output->setFormat('PNG32');
$output->setImageFormat('PNG32');
}
$output->setCompression(Imagick::COMPRESSION_ZIP);
$output->setImageCompression(Imagick::COMPRESSION_ZIP);
if ($this->interlaced) {
$output->setInterlaceScheme(Imagick::INTERLACE_LINE);
}
$result = new EncodedImage($output->getImagesBlob(), 'image/png');
$output->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode png format', previous: $e);
}
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use ImagickException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\TiffEncoder as GenericTiffEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class TiffEncoder extends GenericTiffEncoder implements SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see EncoderInterface::encode()
*
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'TIFF';
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($imagick->getImageCompression());
$imagick->setImageCompression($imagick->getImageCompression());
$imagick->setCompressionQuality($this->quality);
$imagick->setImageCompressionQuality($this->quality);
$result = new EncodedImage($imagick->getImagesBlob(), 'image/tiff');
$imagick->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode tiff format', previous: $e);
}
}
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Encoders;
use Imagick;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Drivers\Imagick\Modifiers\StripMetaModifier;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\WebpEncoder as GenericWebpEncoder;
use Intervention\Image\Exceptions\EncoderException;
use Intervention\Image\Exceptions\StreamException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class WebpEncoder extends GenericWebpEncoder implements SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see EncoderInterface::encode()
*
* @throws InvalidArgumentException
* @throws StreamException
* @throws StateException
* @throws EncoderException
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$format = 'WEBP';
$compression = Imagick::COMPRESSION_ZIP;
// strip meta data
if ($this->strip || (is_null($this->strip) && $this->driver()->config()->strip)) {
$image->modify(new StripMetaModifier());
}
try {
$imagick = clone $image->core()->native();
try {
$imagick->setImageBackgroundColor(new ImagickPixel('transparent'));
} catch (ImagickPixelException $e) {
throw new EncoderException('Failed to encode webp format', previous: $e);
}
if (!$image->isAnimated()) {
$merged = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_MERGE);
$imagick->clear();
$imagick = $merged;
}
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
$imagick->setImageCompressionQuality($this->quality);
if ($this->quality === 100) {
$imagick->setOption('webp:lossless', 'true');
}
$result = new EncodedImage($imagick->getImagesBlob(), 'image/webp');
$imagick->clear();
return $result;
} catch (ImagickException $e) {
throw new EncoderException('Failed to encode webp format', previous: $e);
}
}
}

View file

@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick;
use Imagick;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\AbstractFontProcessor;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\FontInterface;
use Intervention\Image\Interfaces\SizeInterface;
use Intervention\Image\Size;
class FontProcessor extends AbstractFontProcessor
{
/**
* {@inheritdoc}
*
* @see FontProcessorInterface::boxSize()
*
* @throws InvalidArgumentException
* @throws StateException
* @throws DriverException
*/
public function boxSize(string $text, FontInterface $font): SizeInterface
{
// no text - no box size
if (mb_strlen($text) === 0) {
return new Size(0, 0);
}
$draw = $this->toImagickDraw($font);
try {
$dimensions = (new Imagick())->queryFontMetrics($draw, $text);
} catch (ImagickException $e) {
throw new DriverException('Failed query font metrics', previous: $e);
}
return new Size(
intval(round($dimensions['textWidth'])),
intval(round($dimensions['ascender'] + $dimensions['descender'])),
);
}
/**
* Imagick::annotateImage() needs an ImagickDraw object - this method takes
* the font object as the base and adds an optional passed color to the new
* ImagickDraw object.
*
* @throws StateException
* @throws DriverException
*/
public function toImagickDraw(FontInterface $font, ?ImagickPixel $color = null): ImagickDraw
{
if (!$font->hasFile()) {
throw new StateException('No font file specified');
}
try {
$draw = new ImagickDraw();
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
$draw->setFont($font->filepath());
$draw->setFontSize($this->nativeFontSize($font));
$draw->setTextAlignment(Imagick::ALIGN_LEFT);
if ($color instanceof ImagickPixel) {
$draw->setFillColor($color);
}
} catch (ImagickException | ImagickDrawException $e) {
throw new DriverException('Failed to convert font to ImagickDraw instance', previous: $e);
}
return $draw;
}
}

View file

@ -0,0 +1,280 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick;
use Imagick;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Drivers\AbstractFrame;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Image;
use Intervention\Image\Interfaces\DriverInterface;
use Intervention\Image\Interfaces\FrameInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
use Intervention\Image\Size;
class Frame extends AbstractFrame implements FrameInterface
{
/**
* Position this frame was taken from, or null if it is not bound to a
* position in a sequence.
*/
protected ?int $position = null;
/**
* Create new frame.
*
* @throws DriverException
*/
public function __construct(protected Imagick $native)
{
try {
// Imagick::current() returns the wand itself, so a frame taken
// from an animation shares the whole sequence with its core. Keep
// the position it was taken from to be able to seek back to it.
$this->position = $this->native->getIteratorIndex();
$background = new ImagickPixel('rgba(255, 255, 255, 0)');
$this->native->setImageBackgroundColor($background);
$this->native->setBackgroundColor($background);
} catch (ImagickException | ImagickPixelException $e) {
throw new DriverException('Failed to create instance of ' . self::class, previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::toImage()
*
* @throws DriverException
*/
public function toImage(DriverInterface $driver): ImageInterface
{
try {
// The native of a frame taken from an animation still holds the
// whole sequence, and any other frame access in the meantime has
// moved its pointer. Seek back before copying the frame out,
// otherwise the resulting image would report every frame and hold
// whichever one the shared wand was left on.
if ($this->position !== null) {
$this->native->setIteratorIndex($this->position);
}
return new Image($driver, new Core($this->native->getImage()));
} catch (ImagickException $e) {
throw new DriverException('Failed to transform frame into image', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setNative()
*
* @throws InvalidArgumentException
*/
public function setNative(mixed $native): FrameInterface
{
if (!$native instanceof Imagick) {
throw new InvalidArgumentException(
'Value for argument setNative() "$native" must be instanceof of ' . Imagick::class,
);
}
$this->native = $native;
// the replacement carries its own sequence, so the position this
// frame was taken from does not apply to it anymore
$this->position = null;
return $this;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::native()
*/
public function native(): Imagick
{
return $this->native;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::size()
*
* @throws DriverException
*/
public function size(): SizeInterface
{
try {
return new Size(
$this->native->getImageWidth(),
$this->native->getImageHeight(),
);
} catch (ImagickException | InvalidArgumentException $e) {
throw new DriverException('Failed to get frame size', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::delay()
*
* @throws DriverException
*/
public function delay(): float
{
try {
return $this->native->getImageDelay() / 100;
} catch (ImagickException $e) {
throw new DriverException('Failed to get frame delay', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setDelay()
*
* @throws DriverException
*/
public function setDelay(float $delay): FrameInterface
{
try {
$this->native->setImageDelay(intval(round($delay * 100)));
} catch (ImagickException $e) {
throw new DriverException('Failed to set frame disposal method', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::disposalMethod()
*
* @throws DriverException
*/
public function disposalMethod(): int
{
try {
return $this->native->getImageDispose();
} catch (ImagickException $e) {
throw new DriverException('Failed to get frame disposal method', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setDisposalMethod()
*
* @throws InvalidArgumentException
* @throws DriverException
*/
public function setDisposalMethod(int $method): FrameInterface
{
if (!in_array($method, [0, 1, 2, 3])) {
throw new InvalidArgumentException('Value for argument disposal method "$method" must be 0, 1, 2 or 3');
}
try {
$this->native->setImageDispose($method);
} catch (ImagickException $e) {
throw new DriverException('Failed to set frame disposal method', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setOffset()
*
* @throws DriverException
*/
public function setOffset(int $left, int $top): FrameInterface
{
try {
$this->native->setImagePage(
$this->native->getImageWidth(),
$this->native->getImageHeight(),
$left,
$top,
);
} catch (ImagickException $e) {
throw new DriverException('Failed to set frame offset', previous: $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @see DriverInterface::offsetLeft()
*
* @throws DriverException
*/
public function offsetLeft(): int
{
try {
return $this->native->getImagePage()['x'];
} catch (ImagickException $e) {
throw new DriverException('Failed to get frame offset', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setOffsetLeft()
*
* @throws RuntimeException
*/
public function setOffsetLeft(int $offset): FrameInterface
{
return $this->setOffset($offset, $this->offsetTop());
}
/**
* {@inheritdoc}
*
* @see DriverInterface::offsetTop()
*
* @throws DriverException
*/
public function offsetTop(): int
{
try {
return $this->native->getImagePage()['y'];
} catch (ImagickException $e) {
throw new DriverException('Failed to get frame offset', previous: $e);
}
}
/**
* {@inheritdoc}
*
* @see DriverInterface::setOffsetTop()
*
* @throws RuntimeException
*/
public function setOffsetTop(int $offset): FrameInterface
{
return $this->setOffset($this->offsetLeft(), $offset);
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\BlurModifier as GenericBlurModifier;
class BlurModifier extends GenericBlurModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
$result = $frame->native()->blurImage($this->level, 0.5 * $this->level);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to blur image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to blur image',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\BrightnessModifier as GenericBrightnessModifier;
class BrightnessModifier extends GenericBrightnessModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
$result = $frame->native()->modulateImage(100 + $this->level, 100, 100);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image brightness',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image brightness',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ColorizeModifier as GenericColorizeModifier;
class ColorizeModifier extends GenericColorizeModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
$red = $this->normalizeLevel($this->red);
$green = $this->normalizeLevel($this->green);
$blue = $this->normalizeLevel($this->blue);
foreach ($image as $frame) {
try {
$qrange = $frame->native()->getQuantumRange();
} catch (ImageException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to get quantum range',
previous: $e,
);
}
try {
$result = $frame->native()->levelImage(0, $red, $qrange['quantumRangeLong'], Imagick::CHANNEL_RED)
&& $frame->native()->levelImage(0, $green, $qrange['quantumRangeLong'], Imagick::CHANNEL_GREEN)
&& $frame->native()->levelImage(0, $blue, $qrange['quantumRangeLong'], Imagick::CHANNEL_BLUE);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image colors',
);
}
} catch (ImageException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image colors',
previous: $e,
);
}
}
return $image;
}
private function normalizeLevel(int $level): int
{
return $level > 0 ? intval(round($level / 5)) : intval(round(($level + 100) / 100));
}
}

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Error;
use Imagick;
use ImagickException;
use Intervention\Image\Colors\Cmyk\Colorspace as Cmyk;
use Intervention\Image\Colors\Hsl\Colorspace as Hsl;
use Intervention\Image\Colors\Hsv\Colorspace as Hsv;
use Intervention\Image\Colors\Oklab\Colorspace as Oklab;
use Intervention\Image\Colors\Oklch\Colorspace as Oklch;
use Intervention\Image\Colors\Rgb\Colorspace as Rgb;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Interfaces\ColorspaceInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ColorspaceModifier as GenericColorspaceModifier;
class ColorspaceModifier extends GenericColorspaceModifier implements SpecializedInterface
{
/**
* @throws ModifierException
* @throws NotSupportedException
*/
public function apply(ImageInterface $image): ImageInterface
{
$target = $this->imagickColorspaceOrFail($this->targetColorspace());
// Imagick::transformImageColorspace() only affects the frame the
// iterator is currently pointing at, so every frame has to be
// transformed individually. Otherwise all frames but one would keep
// their original colorspace on animated images.
foreach ($image as $frame) {
try {
$result = $frame->native()->transformImageColorspace($target);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to transform image colorspace',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to transform image colorspace',
previous: $e,
);
}
}
return $image;
}
/**
* @throws ModifierException
* @throws NotSupportedException
*/
private function imagickColorspaceOrFail(ColorspaceInterface $colorspace): int
{
if ($colorspace instanceof Rgb) {
return Imagick::COLORSPACE_SRGB;
}
if ($colorspace instanceof Cmyk) {
return Imagick::COLORSPACE_CMYK;
}
if ($colorspace instanceof Hsl) {
return Imagick::COLORSPACE_HSL;
}
if ($colorspace instanceof Hsv) {
return Imagick::COLORSPACE_HSB;
}
try {
if ($colorspace instanceof Oklab && defined(Imagick::class . '::COLORSPACE_OKLAB')) {
return constant(Imagick::class . '::COLORSPACE_OKLAB');
}
if ($colorspace instanceof Oklch && defined(Imagick::class . '::COLORSPACE_OKLCH')) {
return constant(Imagick::class . '::COLORSPACE_OKLCH');
}
} catch (Error $e) {
throw new ModifierException(
'Failed to convert colorspace to Imagick constant',
previous: $e,
);
}
throw new NotSupportedException('Colorspace ' . $colorspace::class . ' is not supported by driver');
}
}

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
class ContainDownModifier extends ContainModifier
{
/**
* Calculate crop size of the contain down resizing process.
*/
protected function cropSize(ImageInterface $image): SizeInterface
{
return $image->size()
->containDown(
$this->width,
$this->height,
)
->alignPivotTo(
$this->resizeSize($image),
$this->alignment,
);
}
}

View file

@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ContainModifier as GenericContainModifier;
class ContainModifier extends GenericContainModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
$crop = $this->cropSize($image);
$resize = $this->resizeSize($image);
$background = $this->driver()->colorProcessor($image)->export($this->backgroundColor());
foreach ($image as $frame) {
$this->scaleFrame($frame->native(), $crop->width(), $crop->height());
$this->setFrameBackgroundTransparent($frame->native());
$this->extendFrame($frame->native(), $resize, $crop);
if ($resize->width() > $crop->width()) {
$this->fillHorizontalAreas($frame->native(), $crop, $resize, $background);
}
if ($resize->height() > $crop->height()) {
$this->fillVerticalAreas($frame->native(), $crop, $resize, $background);
}
}
return $image;
}
/**
* Scale a native Imagick frame to the given dimensions
*
* @throws ModifierException
*/
private function scaleFrame(mixed $native, int $width, int $height): void
{
try {
$result = $native->scaleImage($width, $height);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to resize image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to resize image',
previous: $e,
);
}
}
/**
* Set the background and image background color of a frame to transparent.
*
* @throws ModifierException
*/
private function setFrameBackgroundTransparent(Imagick $native): void
{
try {
$transparent = new ImagickPixel('transparent');
$result = $native->setBackgroundColor($transparent) && $native->setImageBackgroundColor($transparent);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set image background color',
);
}
} catch (ImagickException | ImagickPixelException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set image background color',
previous: $e,
);
}
}
/**
* Extend the canvas of a frame to the resize dimensions using the crop pivot as offset.
*
* @throws ModifierException
*/
private function extendFrame(Imagick $native, SizeInterface $resize, SizeInterface $crop): void
{
try {
$result = $native->extentImage(
$resize->width(),
$resize->height(),
$crop->pivot()->x() * -1,
$crop->pivot()->y() * -1,
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to resize image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to resize image',
previous: $e,
);
}
}
/**
* Fill the left and right background areas that emerged after horizontal extension.
*
* @throws ModifierException
*/
private function fillHorizontalAreas(
Imagick $native,
SizeInterface $crop,
SizeInterface $resize,
ImagickPixel $background,
): void {
try {
$draw = new ImagickDraw();
$draw->setFillColor($background);
$delta = abs($crop->pivot()->x());
if ($delta > 0) {
$draw->rectangle(0, 0, $delta - 1, $resize->height());
}
$draw->rectangle($crop->width() + $delta, 0, $resize->width(), $resize->height());
$result = $native->drawImage($draw);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable fill new image areas with replacement color',
);
}
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable fill new image areas with replacement color',
previous: $e,
);
}
}
/**
* Fill the top and bottom background areas that emerged after vertical extension.
*
* @throws ModifierException
*/
private function fillVerticalAreas(
Imagick $native,
SizeInterface $crop,
SizeInterface $resize,
ImagickPixel $background,
): void {
try {
$draw = new ImagickDraw();
$draw->setFillColor($background);
$delta = abs($crop->pivot()->y());
if ($delta > 0) {
$draw->rectangle(0, 0, $resize->width(), $delta - 1);
}
$draw->rectangle(0, $crop->height() + $delta, $resize->width(), $resize->height());
$result = $native->drawImage($draw);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable fill new image areas with replacement color',
);
}
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable fill new image areas with replacement color',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ContrastModifier as GenericContrastModifier;
class ContrastModifier extends GenericContrastModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// sigmoidalContrastImage's midpoint argument is in QuantumRange units,
// not the [0..1] range a normalized API would imply. Passing 0 pivots
// the sigmoidal curve around pure black, which lifts every pixel
// including the midtone — the opposite of a symmetric contrast
// adjustment. Pivot around the middle of the QuantumRange so a
// mid-grey pixel survives unchanged and the curve is symmetric.
$midpoint = Imagick::QUANTUM_RANGE / 2;
foreach ($image as $frame) {
try {
$result = $frame->native()->sigmoidalContrastImage($this->level > 0, abs($this->level / 4), $midpoint);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image contrast',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image contrast',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\SizeInterface;
class CoverDownModifier extends CoverModifier
{
/**
* Calculate resizing size of the cover down process
*/
protected function resizeSize(SizeInterface $size): SizeInterface
{
return $size->resizeDown($this->width, $this->height);
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\CoverModifier as GenericCoverModifier;
class CoverModifier extends GenericCoverModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
$crop = $this->cropSize($image);
$resize = $this->resizeSize($crop);
foreach ($image as $frame) {
try {
$frame->native()->cropImage(
$crop->width(),
$crop->height(),
$crop->pivot()->x(),
$crop->pivot()->y(),
);
$frame->native()->scaleImage(
$resize->width(),
$resize->height(),
);
$frame->native()->setImagePage(0, 0, 0, 0);
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to resize image',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Colors\Cmyk\Colorspace as Cmyk;
use Intervention\Image\Colors\Hsl\Colorspace as Hsl;
use Intervention\Image\Colors\Hsv\Colorspace as Hsv;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\CropModifier as GenericCropModifier;
class CropModifier extends GenericCropModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
// decode background color
$background = $this->driver()->colorProcessor($image)->export(
$this->backgroundColor(),
);
try {
// create empty container imagick to rebuild core
$imagick = new Imagick();
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to create new imagick instance',
previous: $e,
);
}
// save resolution to add it later
$resolution = $image->resolution()->perInch();
// define position of the image on the new canvas
$crop = $this->crop($image);
$position = [
($crop->pivot()->x() + $this->x) * -1,
($crop->pivot()->y() + $this->y) * -1,
];
foreach ($image as $frame) {
// create new frame canvas with modifiers background
try {
$canvas = new Imagick();
$canvas->newImage($crop->width(), $crop->height(), $background, 'png');
$canvas->setImageResolution($resolution->x(), $resolution->y());
$canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET); // or ALPHACHANNEL_ACTIVATE?
$canvas->setImageColorspace(match ($image->colorspace()::class) {
Cmyk::class => Imagick::COLORSPACE_CMYK,
Hsv::class => Imagick::COLORSPACE_HSB,
Hsl::class => Imagick::COLORSPACE_HSL,
default => Imagick::COLORSPACE_SRGB,
});
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to create new frame canvas',
previous: $e,
);
}
// set animation details
if ($image->isAnimated()) {
try {
$canvas->setImageDelay($frame->native()->getImageDelay());
$canvas->setImageIterations($frame->native()->getImageIterations());
$canvas->setImageDispose($frame->native()->getImageDispose());
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set animation details',
previous: $e,
);
}
}
// make the rectangular position of the original image transparent
// so that we can later place the original on top. this preserves
// the transparency of the original and shows the background color
// of the modifier in the other areas. if the original image has no
// transparent area the rectangular transparency will be covered by
// the original.
try {
$clearer = new Imagick();
$clearer->newImage(
$frame->native()->getImageWidth(),
$frame->native()->getImageHeight(),
new ImagickPixel('black'),
);
$canvas->compositeImage($clearer, Imagick::COMPOSITE_DSTOUT, ...$position);
$clearer->clear();
// place original frame content onto prepared frame canvas
$canvas->compositeImage($frame->native(), Imagick::COMPOSITE_DEFAULT, ...$position);
// add newly built frame to container imagick
$imagick->addImage($canvas);
$canvas->clear();
} catch (ImagickException | ImagickPixelException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to clear transparent areas',
previous: $e,
);
}
}
// replace imagick in the original image
$image->core()->setNative($imagick);
return $image;
}
}

View file

@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawBezierModifier as GenericDrawBezierModifier;
class DrawBezierModifier extends GenericDrawBezierModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws InvalidArgumentException
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$bezierCurve = $this->bezierCurve(
$this->driver()->colorProcessor($image)->export($this->backgroundColor()),
$this->driver()->colorProcessor($image)->export($this->borderColor()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $bezierCurve);
}
return $image;
}
/**
* @throws InvalidArgumentException
* @throws ModifierException
*/
private function bezierCurve(ImagickPixel $backgroundColor, ImagickPixel $borderColor): ImagickDraw
{
try {
$bezierCurve = new ImagickDraw();
$bezierCurve->setFillColor($backgroundColor);
} catch (ImagickDrawException $e) {
throw new ModifierException(
'Failed to build bezier curve',
previous: $e,
);
}
if ($this->drawable->hasBorder() && $this->drawable->borderSize() > 0) {
try {
$bezierCurve->setStrokeColor($borderColor);
$bezierCurve->setStrokeWidth($this->drawable->borderSize());
} catch (ImagickDrawException $e) {
throw new ModifierException(
'Failed to build bezier curve',
previous: $e,
);
}
}
$bezierCurve->pathStart();
$bezierCurve->pathMoveToAbsolute(
$this->drawable->first()->x(),
$this->drawable->first()->y(),
);
match ($this->drawable->count()) {
3 => $bezierCurve->pathCurveToQuadraticBezierAbsolute(
$this->drawable->second()->x(),
$this->drawable->second()->y(),
$this->drawable->last()->x(),
$this->drawable->last()->y(),
),
4 => $bezierCurve->pathCurveToAbsolute(
$this->drawable->second()->x(),
$this->drawable->second()->y(),
$this->drawable->third()->x(),
$this->drawable->third()->y(),
$this->drawable->last()->x(),
$this->drawable->last()->y(),
),
default => throw new InvalidArgumentException(
'You must specify either 3 or 4 points to create a bezier curve',
),
};
$bezierCurve->pathFinish();
return $bezierCurve;
}
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawEllipseModifier as GenericDrawEllipseModifier;
class DrawEllipseModifier extends GenericDrawEllipseModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$ellipse = $this->ellipse(
$this->driver()->colorProcessor($image)->export($this->backgroundColor()),
$this->driver()->colorProcessor($image)->export($this->borderColor()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $ellipse);
}
return $image;
}
/**
* Build drawable ellipse in given colors.
*
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
private function ellipse(ImagickPixel $backgroundColor, ImagickPixel $borderColor): ImagickDraw
{
try {
$drawing = new ImagickDraw();
$drawing->setFillColor($backgroundColor);
if ($this->drawable->hasBorder()) {
$drawing->setStrokeWidth($this->drawable->borderSize());
$drawing->setStrokeColor($borderColor);
}
$drawing->ellipse(
$this->drawable->position()->x(),
$this->drawable->position()->y(),
$this->drawable->width() / 2,
$this->drawable->height() / 2,
0,
360,
);
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to draw ellipse',
previous: $e,
);
}
return $drawing;
}
}

View file

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawLineModifier as GenericDrawLineModifier;
class DrawLineModifier extends GenericDrawLineModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$line = $this->line(
$this->driver()->colorProcessor($image)->export($this->backgroundColor()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $line);
}
return $image;
}
/**
* Build drawable line.
*
* @throws ModifierException
*/
private function line(ImagickPixel $color): ImagickDraw
{
try {
$drawing = new ImagickDraw();
$drawing->setStrokeWidth($this->drawable->width());
$drawing->setFillOpacity(0);
if ($this->drawable->hasBackgroundColor()) {
$drawing->setStrokeColor($color);
}
$drawing->line(
$this->drawable->start()->x(),
$this->drawable->start()->y(),
$this->drawable->end()->x(),
$this->drawable->end()->y(),
);
return $drawing;
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to build ImagickDraw object',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawPixelModifier as GenericDrawPixelModifier;
class DrawPixelModifier extends GenericDrawPixelModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$pixel = $this->pixel(
$this->driver()->colorProcessor($image)->export($this->color()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $pixel);
}
return $image;
}
/**
* Build drawable pixel in given color.
*
* @throws ModifierException
*/
private function pixel(ImagickPixel $color): ImagickDraw
{
try {
$pixel = new ImagickDraw();
$pixel->setFillColor($color);
$pixel->point($this->position->x(), $this->position->y());
return $pixel;
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to build ImagickDraw object',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawPolygonModifier as GenericDrawPolygonModifier;
class DrawPolygonModifier extends GenericDrawPolygonModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$polygon = $this->polygon(
$this->driver()->colorProcessor($image)->export($this->backgroundColor()),
$this->driver()->colorProcessor($image)->export($this->borderColor()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $polygon);
}
return $image;
}
/**
* Create drawable polygon.
*
* @throws ModifierException
*/
private function polygon(ImagickPixel $backgroundColor, ImagickPixel $borderColor): ImagickDraw
{
try {
$polygon = new ImagickDraw();
$polygon->setFillColor($backgroundColor);
if ($this->drawable->hasBorder()) {
$polygon->setStrokeColor($borderColor);
$polygon->setStrokeWidth($this->drawable->borderSize());
}
$polygon->polygon($this->points());
return $polygon;
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to build ImagickDraw object',
previous: $e,
);
}
}
/**
* Return points of drawable in processable form for ImagickDraw.
*
* @return array<array<string, int>>
*/
private function points(): array
{
$points = [];
foreach ($this->drawable as $point) {
$points[] = ['x' => $point->x(), 'y' => $point->y()];
}
return $points;
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use Intervention\Image\Drivers\Imagick\Traits\CanDraw;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawRectangleModifier as GenericDrawRectangleModifier;
class DrawRectangleModifier extends GenericDrawRectangleModifier implements SpecializedInterface
{
use CanDraw;
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$rectangle = $this->rectangle(
$this->driver()->colorProcessor($image)->export($this->backgroundColor()),
$this->driver()->colorProcessor($image)->export($this->borderColor()),
);
foreach ($image as $frame) {
$this->draw($frame->native(), $rectangle);
}
return $image;
}
/**
* Build drawable rectangle.
*
* @throws ModifierException
*/
private function rectangle(ImagickPixel $backgroundColor, ImagickPixel $borderColor): ImagickDraw
{
try {
$drawing = new ImagickDraw();
$drawing->setFillColor($backgroundColor);
if ($this->drawable->hasBorder()) {
$drawing->setStrokeColor($borderColor);
$drawing->setStrokeWidth($this->drawable->borderSize());
}
$drawing->rectangle(
$this->drawable->position()->x(),
$this->drawable->position()->y(),
$this->drawable->position()->x() + $this->drawable->width(),
$this->drawable->position()->y() + $this->drawable->height(),
);
return $drawing;
} catch (ImagickException | ImagickDrawException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to build ImagickDraw object',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickDraw;
use ImagickDrawException;
use ImagickException;
use ImagickPixel;
use ImagickPixelException;
use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\FillModifier as ModifiersFillModifier;
class FillModifier extends ModifiersFillModifier implements SpecializedInterface
{
/**
* @throws ModifierException
* @throws StateException
* @throws ColorDecoderException
*/
public function apply(ImageInterface $image): ImageInterface
{
$pixel = $this->driver()->colorProcessor($image)->export(
$this->color(),
);
foreach ($image->core()->native() as $frame) {
if ($this->hasPosition()) {
$this->floodFillWithColor($frame, $pixel);
} else {
$this->fillAllWithColor($frame, $pixel);
}
}
return $image;
}
/**
* @throws ModifierException
*/
private function floodFillWithColor(Imagick $frame, ImagickPixel $pixel): void
{
try {
$target = $frame->getImagePixelColor(
$this->position->x(),
$this->position->y(),
);
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to find target flood fill color',
previous: $e,
);
}
try {
$result = $frame->floodFillPaintImage(
$pixel,
100,
$target,
$this->position->x(),
$this->position->y(),
false,
Imagick::CHANNEL_ALL,
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to flood fill image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to flood fill image',
previous: $e,
);
}
}
/**
* @throws ModifierException
*/
private function fillAllWithColor(Imagick $frame, ImagickPixel $pixel): void
{
try {
$draw = new ImagickDraw();
$draw->setFillColor($pixel);
$draw->rectangle(0, 0, $frame->getImageWidth(), $frame->getImageHeight());
$frame->drawImage($draw);
} catch (ImagickException | ImagickDrawException | ImagickPixelException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to build ImagickDraw object',
previous: $e,
);
}
try {
// deactive alpha channel when image was filled with opaque color
if ($pixel->getColorValue(Imagick::COLOR_ALPHA) === 1.0) {
$result = $frame->setImageAlphaChannel(Imagick::ALPHACHANNEL_DEACTIVATE);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust alpha channel',
);
}
}
} catch (ImagickException | ImagickPixelException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust alpha channel',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\FillTransparentAreasModifier as GenericFillTransparentAreasModifier;
class FillTransparentAreasModifier extends GenericFillTransparentAreasModifier implements SpecializedInterface
{
/**
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
$backgroundColor = $this->backgroundColor($this->driver());
// get imagickpixel from background color
$pixel = $this->driver()
->colorProcessor($image)
->export($backgroundColor);
// merge transparent areas with the background color
foreach ($image as $frame) {
try {
$frame->native()->setImageBackgroundColor($pixel);
$frame->native()->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$frame->setNative($frame->native()->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN));
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set image background color',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Direction;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\FlipModifier as GenericFlipModifier;
class FlipModifier extends GenericFlipModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
$result = $this->direction === Direction::HORIZONTAL
? $frame->native()->flopImage()
: $frame->native()->flipImage();
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to mirror image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to mirror image',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\GammaModifier as GenericGammaModifier;
class GammaModifier extends GenericGammaModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
$result = $frame->native()->gammaImage($this->gamma);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image gamma',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to adjust image gamma',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\GrayscaleModifier as GenericGrayscaleModifier;
class GrayscaleModifier extends GenericGrayscaleModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
// read the colorspace of the frame to be able to restore it,
// getImageColorspace() only reports the frame the iterator is
// currently pointing at
$colorspace = $frame->native()->getImageColorspace();
// turn image to grayscale
$result = $frame->native()->transformImageColorspace(Imagick::COLORSPACE_GRAY);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to transform image to grayscale',
);
}
// return to the colorspace of the source, grayscale is a color
// operation and is not meant to move the image to another one
$result = $frame->native()->transformImageColorspace($colorspace);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to transform image to grayscale',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to transform image to grayscale',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\InsertModifier as GenericInsertModifier;
use Intervention\Image\Traits\CanConvertRange;
class InsertModifier extends GenericInsertModifier implements SpecializedInterface
{
use CanConvertRange;
/**
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
$watermark = $this->driver()->decodeImage($this->image);
$position = $this->position($image, $watermark);
// set opacity of watermark
if ($this->transparency < 1) {
try {
$opacity = (int) round(self::convertRange($this->transparency, 0, 1, 0, 100));
$alphaEval = $opacity > 0 ? 100 / $opacity : 1000;
$result = $watermark->core()->native()->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET)
&& $watermark->core()->native()->evaluateImage(
Imagick::EVALUATE_DIVIDE,
$alphaEval,
Imagick::CHANNEL_ALPHA,
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set transparency of watermark',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set transparency of watermark',
previous: $e,
);
} catch (RuntimeException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set transparency of watermark',
previous: $e,
);
}
}
foreach ($image as $frame) {
try {
$result = $frame->native()->compositeImage(
$watermark->core()->native(),
Imagick::COMPOSITE_DEFAULT,
$position->x(),
$position->y(),
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to insert watermark image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to insert watermark image',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\InvertModifier as GenericInvertModifier;
class InvertModifier extends GenericInvertModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// Imagick::CHANNEL_DEFAULT includes the alpha channel, so a plain
// negateImage() call inverts transparency along with color and turns
// fully transparent pixels opaque. Mask the alpha bit off so the
// result matches the GD driver, where IMG_FILTER_NEGATE only touches
// the color channels.
$channel = Imagick::CHANNEL_ALL & ~Imagick::CHANNEL_ALPHA;
foreach ($image as $frame) {
try {
$result = $frame->native()->negateImage(false, $channel);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to invert image colors',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to invert image colors',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\OrientModifier as GenericOrientModifier;
class OrientModifier extends GenericOrientModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// getImageOrientation() reads the frame the iterator is pointing at as
// well, so read it off the first frame rather than off whichever one
// the last operation happened to leave it on
$image->core()->native()->setFirstIterator();
$orientation = $image->core()->native()->getImageOrientation();
$orientation = $orientation === Imagick::ORIENTATION_UNDEFINED
? $image->core()->meta()->get('originalImageOrientation', 0)
: $orientation;
// rotateImage() and flopImage() only act on the frame the iterator is
// currently pointing at, so every frame has to be transformed
// individually. Otherwise an animated source comes back with only one
// frame turned and a mixed geometry sequence.
foreach ($image as $frame) {
try {
$result = match ($orientation) {
Imagick::ORIENTATION_TOPRIGHT
=> $frame->native()->flopImage(), // 2
Imagick::ORIENTATION_BOTTOMRIGHT
=> $frame->native()->rotateImage('#000', 180), // 3
Imagick::ORIENTATION_BOTTOMLEFT
=> $frame->native()->rotateImage('#000', 180) && $frame->native()->flopImage(), // 4
Imagick::ORIENTATION_LEFTTOP
=> $frame->native()->rotateImage('#000', 90) && $frame->native()->flopImage(), // 5
Imagick::ORIENTATION_RIGHTTOP
=> $frame->native()->rotateImage('#000', 90), // 6
Imagick::ORIENTATION_RIGHTBOTTOM
=> $frame->native()->rotateImage('#000', 270) && $frame->native()->flopImage(), // 7
Imagick::ORIENTATION_LEFTBOTTOM
=> $frame->native()->rotateImage('#000', 270), // 8
default => true,
};
// set new orientation in frame
$result = $result && $frame->native()->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process rotation of image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process rotation',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use DivisionByZeroError;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\FrameInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\PixelateModifier as GenericPixelateModifier;
class PixelateModifier extends GenericPixelateModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
$this->pixelateFrame($frame);
}
return $image;
}
/**
* @throws ModifierException
*/
protected function pixelateFrame(FrameInterface $frame): void
{
$size = $frame->size();
try {
$result = $frame->native()->scaleImage(
(int) round(max(1, $size->width() / $this->size)),
(int) round(max(1, $size->height() / $this->size)),
) && $frame->native()->scaleImage(
$size->width(),
$size->height(),
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to pixelate image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to pixelate image',
previous: $e,
);
} catch (DivisionByZeroError $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to pixelate image',
previous: $e,
);
}
}
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ProfileModifier as GenericProfileModifier;
class ProfileModifier extends GenericProfileModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// read the profile once, casting it rewinds and drains its stream
$profile = (string) $this->profile;
// profileImage() only acts on the frame the iterator is currently
// pointing at, so every frame has to be profiled individually.
foreach ($image as $frame) {
try {
$result = $frame->native()->profileImage('icc', $profile);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set ICC color profile',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set ICC color profile',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ReduceColorsModifier as GenericReduceColorsModifier;
class ReduceColorsModifier extends GenericReduceColorsModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
if ($this->limit <= 0) {
throw new InvalidArgumentException('Quantization limit must be greater than 0');
}
// no color reduction if the limit is higher than the colors in the img
if ($this->limit > $image->core()->native()->getImageColors()) {
return $image;
}
foreach ($image as $frame) {
try {
$result = $frame->native()->quantizeImage(
$this->limit,
$frame->native()->getImageColorspace(),
0,
false,
false,
);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process quantization',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process quantization',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\RemoveAnimationModifier as GenericRemoveAnimationModifier;
class RemoveAnimationModifier extends GenericRemoveAnimationModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
try {
// create new imagick with just one image
$imagick = new Imagick();
$frame = $this->selectedFrame($image);
$result = $imagick->addImage($frame->native()->getImage());
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to re-apply image frame',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to re-apply image frame',
previous: $e,
);
}
// set new imagick to image
$image->core()->setNative($imagick);
return $image;
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\RemoveProfileModifier as GenericRemoveProfileModifier;
class RemoveProfileModifier extends GenericRemoveProfileModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// profileImage() only acts on the frame the iterator is currently
// pointing at, so every frame has to be cleared individually.
foreach ($image as $frame) {
try {
$result = $frame->native()->profileImage('icc', null);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to remove ICC color profile',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to remove ICC color profile',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ResizeCanvasModifier as GenericResizeCanvasModifier;
class ResizeCanvasModifier extends GenericResizeCanvasModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
$cropSize = $this->cropSize($image);
$image->modify(new CropModifier(
$cropSize->width(),
$cropSize->height(),
$cropSize->pivot()->x(),
$cropSize->pivot()->y(),
$this->backgroundColor(),
));
return $image;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
class ResizeCanvasRelativeModifier extends ResizeCanvasModifier
{
protected function cropSize(ImageInterface $image, bool $relative = false): SizeInterface
{
return parent::cropSize($image, true);
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
class ResizeDownModifier extends ResizeModifier
{
protected function adjustedSize(ImageInterface $image): SizeInterface
{
return $image->size()->resizeDown($this->width, $this->height);
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ResizeModifier as GenericResizeModifier;
class ResizeModifier extends GenericResizeModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
$resizeTo = $this->adjustedSize($image);
foreach ($image as $frame) {
try {
$frame->native()->scaleImage(
$resizeTo->width(),
$resizeTo->height(),
);
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process resizing',
previous: $e,
);
}
}
return $image;
}
protected function adjustedSize(ImageInterface $image): SizeInterface
{
return $image->size()->resize($this->width, $this->height);
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\ResolutionModifier as GenericResolutionModifier;
class ResolutionModifier extends GenericResolutionModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// setImageResolution() only acts on the frame the iterator is
// currently pointing at, so every frame has to be set individually.
foreach ($image as $frame) {
try {
$result = $frame->native()->setImageResolution($this->x, $this->y);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set image resolution',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to set image resolution',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\RotateModifier as GenericRotateModifier;
class RotateModifier extends GenericRotateModifier implements SpecializedInterface
{
/**
* @throws ModifierException
* @throws StateException
*/
public function apply(ImageInterface $image): ImageInterface
{
$background = $this->driver()
->colorProcessor($image)
->export($this->backgroundColor());
foreach ($image as $frame) {
try {
$result = $frame->native()->rotateImage($background, $this->rotationAngle());
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to rotate image',
);
}
// Reset the virtual canvas page that rotateImage() leaves behind. A
// non-right angle produces a negative page offset which otherwise
// corrupts the animated-AVIF (libheif sequences) writer, leaving the
// bottom/right region transparent. Mirrors TrimModifier/CoverModifier.
$frame->native()->setImagePage(0, 0, 0, 0);
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to rotate image',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
class ScaleDownModifier extends ResizeModifier
{
protected function adjustedSize(ImageInterface $image): SizeInterface
{
return $image->size()->scaleDown($this->width, $this->height);
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SizeInterface;
class ScaleModifier extends ResizeModifier
{
protected function adjustedSize(ImageInterface $image): SizeInterface
{
return $image->size()->scale($this->width, $this->height);
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\SharpenModifier as GenericSharpenModifier;
class SharpenModifier extends GenericSharpenModifier implements SpecializedInterface
{
/**
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
foreach ($image as $frame) {
try {
$result = $frame->native()->unsharpMaskImage(1, 1, $this->level / 6.25, 0);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process unsharp mask',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to process unsharp mask',
previous: $e,
);
}
}
return $image;
}
}

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\SliceAnimationModifier as GenericSliceAnimationModifier;
class SliceAnimationModifier extends GenericSliceAnimationModifier implements SpecializedInterface
{
/**
* @throws InvalidArgumentException
*/
public function apply(ImageInterface $image): ImageInterface
{
if ($this->offset >= $image->count()) {
throw new InvalidArgumentException('Offset is not in the range of frames');
}
$image->core()->slice($this->offset, $this->length);
return $image;
}
}

View file

@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use Imagick;
use ImagickException;
use Intervention\Image\Collection;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\ModifierInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
class StripMetaModifier implements ModifierInterface, SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see Intervention\Image\Interfaces\ModifierInterface::apply()
*
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
// getImageProfiles(), stripImage() and profileImage() all act on the
// frame the iterator is currently pointing at, so every frame has to
// be stripped individually. Otherwise the meta data of an animated
// image survives on every frame but one.
foreach ($image as $frame) {
// preserve icc profiles
try {
$profiles = $frame->native()->getImageProfiles('icc');
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to preserve icc profiles',
previous: $e,
);
}
// remove meta data
try {
$result = $frame->native()->stripImage();
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to strip meta data',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to strip meta data',
previous: $e,
);
}
// stripImage() leaves the meta data in the property cache and
// instead sets a "png:exclude-chunk" artifact to keep the png
// encoder from writing it back. That artifact also discards the
// icc profile, because the png encoder skips every profile as
// soon as the text chunks are excluded. Drop the artifact and
// clear the property cache instead, so that the meta data is
// really gone for every encoder and the icc profile can be
// restored below.
try {
if ($frame->native()->getImageArtifact('png:exclude-chunk') !== null) {
$frame->native()->deleteImageArtifact('png:exclude-chunk');
}
$this->clearProperties($frame->native());
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to clear image properties',
previous: $e,
);
}
if ($profiles !== []) {
// re-apply icc profiles
try {
$result = $frame->native()->profileImage("icc", $profiles['icc']);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to re-apply icc profile',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to re-apply icc profile',
previous: $e,
);
}
}
}
$image->setExif(new Collection());
return $image;
}
/**
* Remove all meta data properties of the given image.
*
* @throws ImagickException
*/
private function clearProperties(Imagick $imagick): void
{
foreach ($imagick->getImageProperties('*', false) as $property) {
$this->deleteProperty($imagick, $property);
}
// getImageProperties() silently skips every property whose name starts
// with "[", which a png text chunk is able to produce. The png encoder
// does not skip them, so the ones that are left are read again through
// the "%[*]" format. That format builds a string of every property and
// its value, which is why it only runs once the properties above are
// gone and there is almost never anything left to report.
foreach (explode("\n", (string) $imagick->identifyFormat('%[*]')) as $line) {
$position = strpos($line, '=');
if ($position !== false && $position > 0) {
$this->deleteProperty($imagick, substr($line, 0, $position));
}
}
}
/**
* Remove the given property of the given image unless it is an encoder hint.
*
* @throws ImagickException
*/
private function deleteProperty(Imagick $imagick, string $property): void
{
// the png encoder skips "png:" and "jpeg:" properties, they carry
// encoding hints like the jpeg sampling factor instead of meta data
if (str_starts_with($property, 'png:') || str_starts_with($property, 'jpeg:')) {
return;
}
$imagick->deleteImageProperty($property);
}
}

View file

@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickDraw;
use Intervention\Image\Drivers\Imagick\FontProcessor;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\InvalidArgumentException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Geometry\Point;
use Intervention\Image\Interfaces\FontInterface;
use Intervention\Image\Interfaces\FrameInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\PointInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\TextModifier as GenericTextModifier;
use Intervention\Image\Typography\Line;
class TextModifier extends GenericTextModifier implements SpecializedInterface
{
/**
* {@inheritdoc}
*
* @see ModifierInterface::apply()
*
* @throws InvalidArgumentException
* @throws StateException
* @throws DriverException
* @throws ModifierException
* @throws RuntimeException
*/
public function apply(ImageInterface $image): ImageInterface
{
$lines = $this->processor()->textBlock($this->text, $this->font, $this->position);
$drawText = $this->imagickDrawText($image, $this->font);
$drawStroke = $this->imagickDrawStroke($image, $this->font);
foreach ($image as $frame) {
foreach ($lines as $line) {
foreach ($this->strokeOffsets($this->font) as $offset) {
// Draw the stroke outline under the actual text
$this->maybeDrawTextline($frame, $line, $drawStroke, $offset);
}
// Draw the actual text
$this->maybeDrawTextline($frame, $line, $drawText);
}
}
return $image;
}
/**
* Create an ImagickDraw object to draw text on the image
*
* @throws StateException
* @throws DriverException
* @throws RuntimeException
*/
private function imagickDrawText(ImageInterface $image, FontInterface $font): ImagickDraw
{
$color = $this->driver()->decodeColor($font->color());
if ($font->hasStrokeEffect() && $color->isTransparent()) {
throw new StateException(
'The text color must be fully opaque when using the stroke effect',
);
}
$color = $this->driver()->colorProcessor($image)->export($color);
return $this->processor()->toImagickDraw($font, $color);
}
/**
* Create a ImagickDraw object to draw the outline stroke effect on the Image
*
* @throws StateException
* @throws DriverException
* @throws RuntimeException
*/
private function imagickDrawStroke(ImageInterface $image, FontInterface $font): ?ImagickDraw
{
if (!$font->hasStrokeEffect()) {
return null;
}
$color = $this->driver()->decodeColor($font->strokeColor());
if ($color->isTransparent()) {
throw new StateException(
'The stroke color must be fully opaque',
);
}
$color = $this->driver()->colorProcessor($image)->export($color);
return $this->processor()->toImagickDraw($font, $color);
}
/**
* Maybe draw given line of text on frame instance depending on given
* ImageDraw instance. Optionally move line position by given offset.
*
* @throws ModifierException
*/
private function maybeDrawTextline(
FrameInterface $frame,
Line $textline,
?ImagickDraw $draw = null,
PointInterface $offset = new Point(),
): void {
if ($draw instanceof ImagickDraw) {
try {
$result = $frame->native()->annotateImage(
$draw,
$textline->position()->x() + $offset->x(),
$textline->position()->y() + $offset->y(),
$this->font->angle(),
(string) $textline,
);
} catch (ImageException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to draw text line',
previous: $e,
);
}
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to draw text line',
);
}
}
}
/**
* Return imagick font processor
*
* @throws DriverException
* @throws StateException
*/
private function processor(): FontProcessor
{
$processor = $this->driver()->fontProcessor();
if (!$processor instanceof FontProcessor) {
throw new DriverException('Font processor does not match the driver');
}
return $processor;
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Modifiers;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\TrimModifier as GenericTrimModifier;
class TrimModifier extends GenericTrimModifier implements SpecializedInterface
{
/**
* @throws NotSupportedException
* @throws ModifierException
*/
public function apply(ImageInterface $image): ImageInterface
{
if ($image->isAnimated()) {
throw new NotSupportedException('Trim modifier cannot be applied to animated images');
}
$imagick = $image->core()->native();
try {
$result = $imagick->trimImage(($this->tolerance / 100 * $imagick->getQuantum()) / 1.5)
&& $imagick->setImagePage(0, 0, 0, 0);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to processs image trimming',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to processs image trimming',
previous: $e,
);
}
return $image;
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Intervention\Image\Drivers\Imagick\Traits;
use Imagick;
use ImagickDraw;
use ImagickException;
use Intervention\Image\Exceptions\ModifierException;
trait CanDraw
{
/**
* Draw given element on canvas.
*
* @throws ModifierException
*/
protected function draw(Imagick $canvas, ImagickDraw $element): void
{
try {
$result = $canvas->drawImage($element);
if ($result === false) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to draw pixel on image',
);
}
} catch (ImagickException $e) {
throw new ModifierException(
'Failed to apply ' . self::class . ', unable to draw pixel on image',
previous: $e,
);
}
}
}