Added: Incorrect image orientation

This commit is contained in:
RainLoop Team 2015-10-29 23:02:58 +03:00
parent 217207883f
commit e3b62d24d8
87 changed files with 10461 additions and 21 deletions

View file

@ -0,0 +1,356 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Draw\DrawerInterface;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Exception\NotSupportedException;
use Imagine\Exception\RuntimeException;
use Imagine\Image\AbstractFont;
use Imagine\Image\BoxInterface;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\Point;
use Imagine\Image\PointInterface;
/**
* Drawer implementation using the Gmagick PHP extension
*/
final class Drawer implements DrawerInterface
{
/**
* @var \Gmagick
*/
private $gmagick;
/**
* @param \Gmagick $gmagick
*/
public function __construct(\Gmagick $gmagick)
{
$this->gmagick = $gmagick;
}
/**
* {@inheritdoc}
*/
public function arc(PointInterface $center, BoxInterface $size, $start, $end, ColorInterface $color, $thickness = 1)
{
$x = $center->getX();
$y = $center->getY();
$width = $size->getWidth();
$height = $size->getHeight();
try {
$pixel = $this->getColor($color);
$arc = new \GmagickDraw();
$arc->setstrokecolor($pixel);
$arc->setstrokewidth(max(1, (int) $thickness));
$arc->setfillcolor('transparent');
$arc->arc(
$x - $width / 2,
$y - $height / 2,
$x + $width / 2,
$y + $height / 2,
$start,
$end
);
$this->gmagick->drawImage($arc);
$pixel = null;
$arc = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Draw arc operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function chord(PointInterface $center, BoxInterface $size, $start, $end, ColorInterface $color, $fill = false, $thickness = 1)
{
$x = $center->getX();
$y = $center->getY();
$width = $size->getWidth();
$height = $size->getHeight();
try {
$pixel = $this->getColor($color);
$chord = new \GmagickDraw();
$chord->setstrokecolor($pixel);
$chord->setstrokewidth(max(1, (int) $thickness));
if ($fill) {
$chord->setfillcolor($pixel);
} else {
$x1 = round($x + $width / 2 * cos(deg2rad($start)));
$y1 = round($y + $height / 2 * sin(deg2rad($start)));
$x2 = round($x + $width / 2 * cos(deg2rad($end)));
$y2 = round($y + $height / 2 * sin(deg2rad($end)));
$this->line(new Point($x1, $y1), new Point($x2, $y2), $color);
$chord->setfillcolor('transparent');
}
$chord->arc($x - $width / 2, $y - $height / 2, $x + $width / 2, $y + $height / 2, $start, $end);
$this->gmagick->drawImage($chord);
$pixel = null;
$chord = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Draw chord operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function ellipse(PointInterface $center, BoxInterface $size, ColorInterface $color, $fill = false, $thickness = 1)
{
$width = $size->getWidth();
$height = $size->getHeight();
try {
$pixel = $this->getColor($color);
$ellipse = new \GmagickDraw();
$ellipse->setstrokecolor($pixel);
$ellipse->setstrokewidth(max(1, (int) $thickness));
if ($fill) {
$ellipse->setfillcolor($pixel);
} else {
$ellipse->setfillcolor('transparent');
}
$ellipse->ellipse(
$center->getX(),
$center->getY(),
$width / 2,
$height / 2,
0, 360
);
$this->gmagick->drawImage($ellipse);
$pixel = null;
$ellipse = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Draw ellipse operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function line(PointInterface $start, PointInterface $end, ColorInterface $color, $thickness = 1)
{
try {
$pixel = $this->getColor($color);
$line = new \GmagickDraw();
$line->setstrokecolor($pixel);
$line->setstrokewidth(max(1, (int) $thickness));
$line->setfillcolor($pixel);
$line->line(
$start->getX(),
$start->getY(),
$end->getX(),
$end->getY()
);
$this->gmagick->drawImage($line);
$pixel = null;
$line = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Draw line operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function pieSlice(PointInterface $center, BoxInterface $size, $start, $end, ColorInterface $color, $fill = false, $thickness = 1)
{
$width = $size->getWidth();
$height = $size->getHeight();
$x1 = round($center->getX() + $width / 2 * cos(deg2rad($start)));
$y1 = round($center->getY() + $height / 2 * sin(deg2rad($start)));
$x2 = round($center->getX() + $width / 2 * cos(deg2rad($end)));
$y2 = round($center->getY() + $height / 2 * sin(deg2rad($end)));
if ($fill) {
$this->chord($center, $size, $start, $end, $color, true, $thickness);
$this->polygon(
array(
$center,
new Point($x1, $y1),
new Point($x2, $y2),
),
$color,
true,
$thickness
);
} else {
$this->arc($center, $size, $start, $end, $color, $thickness);
$this->line($center, new Point($x1, $y1), $color, $thickness);
$this->line($center, new Point($x2, $y2), $color, $thickness);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function dot(PointInterface $position, ColorInterface $color)
{
$x = $position->getX();
$y = $position->getY();
try {
$pixel = $this->getColor($color);
$point = new \GmagickDraw();
$point->setfillcolor($pixel);
$point->point($x, $y);
$this->gmagick->drawimage($point);
$pixel = null;
$point = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Draw point operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function polygon(array $coordinates, ColorInterface $color, $fill = false, $thickness = 1)
{
if (count($coordinates) < 3) {
throw new InvalidArgumentException(sprintf('Polygon must consist of at least 3 coordinates, %d given', count($coordinates)));
}
$points = array_map(function (PointInterface $p) {
return array('x' => $p->getX(), 'y' => $p->getY());
}, $coordinates);
try {
$pixel = $this->getColor($color);
$polygon = new \GmagickDraw();
$polygon->setstrokecolor($pixel);
$polygon->setstrokewidth(max(1, (int) $thickness));
if ($fill) {
$polygon->setfillcolor($pixel);
} else {
$polygon->setfillcolor('transparent');
}
$polygon->polygon($points);
$this->gmagick->drawImage($polygon);
unset($pixel, $polygon);
} catch (\GmagickException $e) {
throw new RuntimeException('Draw polygon operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function text($string, AbstractFont $font, PointInterface $position, $angle = 0, $width = null)
{
try {
$pixel = $this->getColor($font->getColor());
$text = new \GmagickDraw();
$text->setfont($font->getFile());
/**
* @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027
*
* ensure font resolution is the same as GD's hard-coded 96
*/
$text->setfontsize((int) ($font->getSize() * (96 / 72)));
$text->setfillcolor($pixel);
$info = $this->gmagick->queryfontmetrics($text, $string);
$rad = deg2rad($angle);
$cos = cos($rad);
$sin = sin($rad);
$x1 = round(0 * $cos - 0 * $sin);
$x2 = round($info['textWidth'] * $cos - $info['textHeight'] * $sin);
$y1 = round(0 * $sin + 0 * $cos);
$y2 = round($info['textWidth'] * $sin + $info['textHeight'] * $cos);
$xdiff = 0 - min($x1, $x2);
$ydiff = 0 - min($y1, $y2);
if ($width !== null) {
throw new NotSupportedException('Gmagick doesn\'t support queryfontmetrics function for multiline text', 1);
}
$this->gmagick->annotateimage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string);
unset($pixel, $text);
} catch (\GmagickException $e) {
throw new RuntimeException('Draw text operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* Gets specifically formatted color string from Color instance
*
* @param ColorInterface $color
*
* @return \GmagickPixel
*
* @throws InvalidArgumentException In case a non-opaque color is passed
*/
private function getColor(ColorInterface $color)
{
if (!$color->isOpaque()) {
throw new InvalidArgumentException('Gmagick doesn\'t support transparency');
}
return new \GmagickPixel((string) $color);
}
}

View file

@ -0,0 +1,106 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Effects\EffectsInterface;
use Imagine\Exception\RuntimeException;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Exception\NotSupportedException;
/**
* Effects implementation using the Gmagick PHP extension
*/
class Effects implements EffectsInterface
{
private $gmagick;
public function __construct(\Gmagick $gmagick)
{
$this->gmagick = $gmagick;
}
/**
* {@inheritdoc}
*/
public function gamma($correction)
{
try {
$this->gmagick->gammaimage($correction);
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to apply gamma correction to the image');
}
return $this;
}
/**
* {@inheritdoc}
*/
public function negative()
{
if (!method_exists($this->gmagick, 'negateimage')) {
throw new NotSupportedException('Gmagick version 1.1.0 RC3 is required for negative effect');
}
try {
$this->gmagick->negateimage(false, \Gmagick::CHANNEL_ALL);
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to negate the image');
}
return $this;
}
/**
* {@inheritdoc}
*/
public function grayscale()
{
try {
$this->gmagick->setImageType(2);
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to grayscale the image');
}
return $this;
}
/**
* {@inheritdoc}
*/
public function colorize(ColorInterface $color)
{
throw new NotSupportedException('Gmagick does not support colorize');
}
/**
* {@inheritdoc}
*/
public function sharpen()
{
throw new NotSupportedException('Gmagick does not support sharpen yet');
}
/**
* {@inheritdoc}
*/
public function blur($sigma = 1)
{
try {
$this->gmagick->blurImage(0, $sigma);
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to blur the image', $e->getCode(), $e);
}
return $this;
}
}

View file

@ -0,0 +1,63 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Image\AbstractFont;
use Imagine\Image\Box;
use Imagine\Image\Palette\Color\ColorInterface;
/**
* Font implementation using the Gmagick PHP extension
*/
final class Font extends AbstractFont
{
/**
* @var \Gmagick
*/
private $gmagick;
/**
* @param \Gmagick $gmagick
* @param string $file
* @param integer $size
* @param ColorInterface $color
*/
public function __construct(\Gmagick $gmagick, $file, $size, ColorInterface $color)
{
$this->gmagick = $gmagick;
parent::__construct($file, $size, $color);
}
/**
* {@inheritdoc}
*/
public function box($string, $angle = 0)
{
$text = new \GmagickDraw();
$text->setfont($this->file);
/**
* @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027
*
* ensure font resolution is the same as GD's hard-coded 96
*/
$text->setfontsize((int) ($this->size * (96 / 72)));
$text->setfontstyle(\Gmagick::STYLE_OBLIQUE);
$info = $this->gmagick->queryfontmetrics($text, $string);
$box = new Box($info['textWidth'], $info['textHeight']);
return $box;
}
}

View file

@ -0,0 +1,786 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Exception\OutOfBoundsException;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Exception\RuntimeException;
use Imagine\Image\AbstractImage;
use Imagine\Image\Metadata\MetadataBag;
use Imagine\Image\Palette\PaletteInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\Box;
use Imagine\Image\BoxInterface;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\Fill\FillInterface;
use Imagine\Image\Point;
use Imagine\Image\PointInterface;
use Imagine\Image\ProfileInterface;
/**
* Image implementation using the Gmagick PHP extension
*/
final class Image extends AbstractImage
{
/**
* @var \Gmagick
*/
private $gmagick;
/**
* @var Layers
*/
private $layers;
/**
* @var PaletteInterface
*/
private $palette;
private static $colorspaceMapping = array(
PaletteInterface::PALETTE_CMYK => \Gmagick::COLORSPACE_CMYK,
PaletteInterface::PALETTE_RGB => \Gmagick::COLORSPACE_RGB,
);
/**
* Constructs a new Image instance
*
* @param \Gmagick $gmagick
* @param PaletteInterface $palette
* @param MetadataBag $metadata
*/
public function __construct(\Gmagick $gmagick, PaletteInterface $palette, MetadataBag $metadata)
{
$this->metadata = $metadata;
$this->gmagick = $gmagick;
$this->setColorspace($palette);
$this->layers = new Layers($this, $this->palette, $this->gmagick);
}
/**
* Destroys allocated gmagick resources
*/
public function __destruct()
{
if ($this->gmagick instanceof \Gmagick) {
$this->gmagick->clear();
$this->gmagick->destroy();
}
}
/**
* Returns gmagick instance
*
* @return Gmagick
*/
public function getGmagick()
{
return $this->gmagick;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function copy()
{
return new self(clone $this->gmagick, $this->palette, clone $this->metadata);
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function crop(PointInterface $start, BoxInterface $size)
{
if (!$start->in($this->getSize())) {
throw new OutOfBoundsException('Crop coordinates must start at minimum 0, 0 position from top left corner, crop height and width must be positive integers and must not exceed the current image borders');
}
try {
$this->gmagick->cropimage($size->getWidth(), $size->getHeight(), $start->getX(), $start->getY());
} catch (\GmagickException $e) {
throw new RuntimeException('Crop operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function flipHorizontally()
{
try {
$this->gmagick->flopimage();
} catch (\GmagickException $e) {
throw new RuntimeException('Horizontal flip operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function flipVertically()
{
try {
$this->gmagick->flipimage();
} catch (\GmagickException $e) {
throw new RuntimeException('Vertical flip operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function strip()
{
try {
try {
$this->profile($this->palette->profile());
} catch (\Exception $e) {
// here we discard setting the profile as the previous incorporated profile
// is corrupted, let's now strip the image
}
$this->gmagick->stripimage();
} catch (\GmagickException $e) {
throw new RuntimeException('Strip operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function paste(ImageInterface $image, PointInterface $start)
{
if (!$image instanceof self) {
throw new InvalidArgumentException(sprintf('Gmagick\Image can only paste() Gmagick\Image instances, %s given', get_class($image)));
}
if (!$this->getSize()->contains($image->getSize(), $start)) {
throw new OutOfBoundsException('Cannot paste image of the given size at the specified position, as it moves outside of the current image\'s box');
}
try {
$this->gmagick->compositeimage($image->gmagick, \Gmagick::COMPOSITE_DEFAULT, $start->getX(), $start->getY());
} catch (\GmagickException $e) {
throw new RuntimeException('Paste operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function resize(BoxInterface $size, $filter = ImageInterface::FILTER_UNDEFINED)
{
static $supportedFilters = array(
ImageInterface::FILTER_UNDEFINED => \Gmagick::FILTER_UNDEFINED,
ImageInterface::FILTER_BESSEL => \Gmagick::FILTER_BESSEL,
ImageInterface::FILTER_BLACKMAN => \Gmagick::FILTER_BLACKMAN,
ImageInterface::FILTER_BOX => \Gmagick::FILTER_BOX,
ImageInterface::FILTER_CATROM => \Gmagick::FILTER_CATROM,
ImageInterface::FILTER_CUBIC => \Gmagick::FILTER_CUBIC,
ImageInterface::FILTER_GAUSSIAN => \Gmagick::FILTER_GAUSSIAN,
ImageInterface::FILTER_HANNING => \Gmagick::FILTER_HANNING,
ImageInterface::FILTER_HAMMING => \Gmagick::FILTER_HAMMING,
ImageInterface::FILTER_HERMITE => \Gmagick::FILTER_HERMITE,
ImageInterface::FILTER_LANCZOS => \Gmagick::FILTER_LANCZOS,
ImageInterface::FILTER_MITCHELL => \Gmagick::FILTER_MITCHELL,
ImageInterface::FILTER_POINT => \Gmagick::FILTER_POINT,
ImageInterface::FILTER_QUADRATIC => \Gmagick::FILTER_QUADRATIC,
ImageInterface::FILTER_SINC => \Gmagick::FILTER_SINC,
ImageInterface::FILTER_TRIANGLE => \Gmagick::FILTER_TRIANGLE
);
if (!array_key_exists($filter, $supportedFilters)) {
throw new InvalidArgumentException('Unsupported filter type');
}
try {
$this->gmagick->resizeimage($size->getWidth(), $size->getHeight(), $supportedFilters[$filter], 1);
} catch (\GmagickException $e) {
throw new RuntimeException('Resize operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function rotate($angle, ColorInterface $background = null)
{
try {
$background = $background ?: $this->palette->color('fff');
$pixel = $this->getColor($background);
$this->gmagick->rotateimage($pixel, $angle);
unset($pixel);
} catch (\GmagickException $e) {
throw new RuntimeException('Rotate operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* Internal
*
* Applies options before save or output
*
* @param \Gmagick $image
* @param array $options
* @param string $path
*
* @throws InvalidArgumentException
*/
private function applyImageOptions(\Gmagick $image, array $options, $path)
{
if (isset($options['format'])) {
$format = $options['format'];
} elseif ('' !== $extension = pathinfo($path, \PATHINFO_EXTENSION)) {
$format = $extension;
} else {
$format = pathinfo($image->getImageFilename(), \PATHINFO_EXTENSION);
}
$format = strtolower($format);
$options = $this->updateSaveOptions($options);
if (isset($options['jpeg_quality']) && in_array($format, array('jpeg', 'jpg', 'pjpeg'))) {
$image->setCompressionQuality($options['jpeg_quality']);
}
if ((isset($options['png_compression_level']) || isset($options['png_compression_filter'])) && $format === 'png') {
// first digit: compression level (default: 7)
if (isset($options['png_compression_level'])) {
if ($options['png_compression_level'] < 0 || $options['png_compression_level'] > 9) {
throw new InvalidArgumentException('png_compression_level option should be an integer from 0 to 9');
}
$compression = $options['png_compression_level'] * 10;
} else {
$compression = 70;
}
// second digit: compression filter (default: 5)
if (isset($options['png_compression_filter'])) {
if ($options['png_compression_filter'] < 0 || $options['png_compression_filter'] > 9) {
throw new InvalidArgumentException('png_compression_filter option should be an integer from 0 to 9');
}
$compression += $options['png_compression_filter'];
} else {
$compression += 5;
}
$image->setCompressionQuality($compression);
}
if (isset($options['resolution-units']) && isset($options['resolution-x']) && isset($options['resolution-y'])) {
if ($options['resolution-units'] == ImageInterface::RESOLUTION_PIXELSPERCENTIMETER) {
$image->setimageunits(\Gmagick::RESOLUTION_PIXELSPERCENTIMETER);
} elseif ($options['resolution-units'] == ImageInterface::RESOLUTION_PIXELSPERINCH) {
$image->setimageunits(\Gmagick::RESOLUTION_PIXELSPERINCH);
} else {
throw new InvalidArgumentException('Unsupported image unit format');
}
$image->setimageresolution($options['resolution-x'], $options['resolution-y']);
}
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function save($path = null, array $options = array())
{
$path = null === $path ? $this->gmagick->getImageFilename() : $path;
if ('' === trim($path)) {
throw new RuntimeException('You can omit save path only if image has been open from a file');
}
try {
$this->prepareOutput($options, $path);
$allFrames = !isset($options['animated']) || false === $options['animated'];
$this->gmagick->writeimage($path, $allFrames);
} catch (\GmagickException $e) {
throw new RuntimeException('Save operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function show($format, array $options = array())
{
header('Content-type: '.$this->getMimeType($format));
echo $this->get($format, $options);
return $this;
}
/**
* {@inheritdoc}
*/
public function get($format, array $options = array())
{
try {
$options['format'] = $format;
$this->prepareOutput($options);
} catch (\GmagickException $e) {
throw new RuntimeException('Get operation failed', $e->getCode(), $e);
}
return $this->gmagick->getimagesblob();
}
/**
* @param array $options
* @param string $path
*/
private function prepareOutput(array $options, $path = null)
{
if (isset($options['format'])) {
$this->gmagick->setimageformat($options['format']);
}
if (isset($options['animated']) && true === $options['animated']) {
$format = isset($options['format']) ? $options['format'] : 'gif';
$delay = isset($options['animated.delay']) ? $options['animated.delay'] : null;
$loops = isset($options['animated.loops']) ? $options['animated.loops'] : 0;
$options['flatten'] = false;
$this->layers->animate($format, $delay, $loops);
} else {
$this->layers->merge();
}
$this->applyImageOptions($this->gmagick, $options, $path);
// flatten only if image has multiple layers
if ((!isset($options['flatten']) || $options['flatten'] === true) && count($this->layers) > 1) {
$this->flatten();
}
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->get('png');
}
/**
* {@inheritdoc}
*/
public function draw()
{
return new Drawer($this->gmagick);
}
/**
* {@inheritdoc}
*/
public function effects()
{
return new Effects($this->gmagick);
}
/**
* {@inheritdoc}
*/
public function getSize()
{
try {
$i = $this->gmagick->getimageindex();
$this->gmagick->setimageindex(0); //rewind
$width = $this->gmagick->getimagewidth();
$height = $this->gmagick->getimageheight();
$this->gmagick->setimageindex($i);
} catch (\GmagickException $e) {
throw new RuntimeException('Get size operation failed', $e->getCode(), $e);
}
return new Box($width, $height);
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function applyMask(ImageInterface $mask)
{
if (!$mask instanceof self) {
throw new InvalidArgumentException('Can only apply instances of Imagine\Gmagick\Image as masks');
}
$size = $this->getSize();
$maskSize = $mask->getSize();
if ($size != $maskSize) {
throw new InvalidArgumentException(sprintf('The given mask doesn\'t match current image\'s size, current mask\'s dimensions are %s, while image\'s dimensions are %s', $maskSize, $size));
}
try {
$mask = $mask->copy();
$this->gmagick->compositeimage($mask->gmagick, \Gmagick::COMPOSITE_DEFAULT, 0, 0);
} catch (\GmagickException $e) {
throw new RuntimeException('Apply mask operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function mask()
{
$mask = $this->copy();
try {
$mask->gmagick->modulateimage(100, 0, 100);
} catch (\GmagickException $e) {
throw new RuntimeException('Mask operation failed', $e->getCode(), $e);
}
return $mask;
}
/**
* {@inheritdoc}
*
* @return ImageInterface
*/
public function fill(FillInterface $fill)
{
try {
$draw = new \GmagickDraw();
$size = $this->getSize();
$w = $size->getWidth();
$h = $size->getHeight();
for ($x = 0; $x <= $w; $x++) {
for ($y = 0; $y <= $h; $y++) {
$pixel = $this->getColor($fill->getColor(new Point($x, $y)));
$draw->setfillcolor($pixel);
$draw->point($x, $y);
$pixel = null;
}
}
$this->gmagick->drawimage($draw);
$draw = null;
} catch (\GmagickException $e) {
throw new RuntimeException('Fill operation failed', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function histogram()
{
try {
$pixels = $this->gmagick->getimagehistogram();
} catch (\GmagickException $e) {
throw new RuntimeException('Error while fetching histogram', $e->getCode(), $e);
}
$image = $this;
return array_map(function (\GmagickPixel $pixel) use ($image) {
return $image->pixelToColor($pixel);
}, $pixels);
}
/**
* {@inheritdoc}
*/
public function getColorAt(PointInterface $point)
{
if (!$point->in($this->getSize())) {
throw new InvalidArgumentException(sprintf('Error getting color at point [%s,%s]. The point must be inside the image of size [%s,%s]', $point->getX(), $point->getY(), $this->getSize()->getWidth(), $this->getSize()->getHeight()));
}
try {
$cropped = clone $this->gmagick;
$histogram = $cropped
->cropImage(1, 1, $point->getX(), $point->getY())
->getImageHistogram();
} catch (\GmagickException $e) {
throw new RuntimeException('Unable to get the pixel');
}
$pixel = array_shift($histogram);
unset($histogram, $cropped);
return $this->pixelToColor($pixel);
}
/**
* Returns a color given a pixel, depending the Palette context
*
* Note : this method is public for PHP 5.3 compatibility
*
* @param \GmagickPixel $pixel
*
* @return ColorInterface
*
* @throws InvalidArgumentException In case a unknown color is requested
*/
public function pixelToColor(\GmagickPixel $pixel)
{
static $colorMapping = array(
ColorInterface::COLOR_RED => \Gmagick::COLOR_RED,
ColorInterface::COLOR_GREEN => \Gmagick::COLOR_GREEN,
ColorInterface::COLOR_BLUE => \Gmagick::COLOR_BLUE,
ColorInterface::COLOR_CYAN => \Gmagick::COLOR_CYAN,
ColorInterface::COLOR_MAGENTA => \Gmagick::COLOR_MAGENTA,
ColorInterface::COLOR_YELLOW => \Gmagick::COLOR_YELLOW,
ColorInterface::COLOR_KEYLINE => \Gmagick::COLOR_BLACK,
// There is no gray component in \Gmagick, let's use one of the RGB comp
ColorInterface::COLOR_GRAY => \Gmagick::COLOR_RED,
);
if ($this->palette->supportsAlpha()) {
try {
$alpha = (int) round($pixel->getcolorvalue(\Gmagick::COLOR_ALPHA) * 100);
} catch (\GmagickPixelException $e) {
$alpha = null;
}
} else {
$alpha = null;
}
$palette = $this->palette();
return $this->palette->color(array_map(function ($color) use ($palette, $pixel, $colorMapping) {
if (!isset($colorMapping[$color])) {
throw new InvalidArgumentException(sprintf('Color %s is not mapped in Gmagick', $color));
}
$multiplier = 255;
if ($palette->name() === PaletteInterface::PALETTE_CMYK) {
$multiplier = 100;
}
return $pixel->getcolorvalue($colorMapping[$color]) * $multiplier;
}, $this->palette->pixelDefinition()), $alpha);
}
/**
* {@inheritdoc}
*/
public function layers()
{
return $this->layers;
}
/**
* {@inheritdoc}
*/
public function interlace($scheme)
{
static $supportedInterlaceSchemes = array(
ImageInterface::INTERLACE_NONE => \Gmagick::INTERLACE_NO,
ImageInterface::INTERLACE_LINE => \Gmagick::INTERLACE_LINE,
ImageInterface::INTERLACE_PLANE => \Gmagick::INTERLACE_PLANE,
ImageInterface::INTERLACE_PARTITION => \Gmagick::INTERLACE_PARTITION,
);
if (!array_key_exists($scheme, $supportedInterlaceSchemes)) {
throw new InvalidArgumentException('Unsupported interlace type');
}
$this->gmagick->setInterlaceScheme($supportedInterlaceSchemes[$scheme]);
return $this;
}
/**
* {@inheritdoc}
*/
public function usePalette(PaletteInterface $palette)
{
if (!isset(static::$colorspaceMapping[$palette->name()])) {
throw new InvalidArgumentException(sprintf('The palette %s is not supported by Gmagick driver',$palette->name()));
}
if ($this->palette->name() === $palette->name()) {
return $this;
}
try {
try {
$hasICCProfile = (Boolean) $this->gmagick->getimageprofile('ICM');
} catch (\GmagickException $e) {
$hasICCProfile = false;
}
if (!$hasICCProfile) {
$this->profile($this->palette->profile());
}
$this->profile($palette->profile());
$this->setColorspace($palette);
$this->palette = $palette;
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to set colorspace', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function palette()
{
return $this->palette;
}
/**
* {@inheritdoc}
*/
public function profile(ProfileInterface $profile)
{
try {
$this->gmagick->profileimage('ICM', $profile->data());
} catch (\GmagickException $e) {
throw new RuntimeException(sprintf('Unable to add profile %s to image', $profile->name()), $e->getCode(), $e);
}
return $this;
}
/**
* Internal
*
* Flatten the image.
*/
private function flatten()
{
/**
* @see http://pecl.php.net/bugs/bug.php?id=22435
*/
if (method_exists($this->gmagick, 'flattenImages')) {
try {
$this->gmagick = $this->gmagick->flattenImages();
} catch (\GmagickException $e) {
throw new RuntimeException('Flatten operation failed', $e->getCode(), $e);
}
}
}
/**
* Gets specifically formatted color string from Color instance
*
* @param ColorInterface $color
*
* @return \GmagickPixel
*
* @throws InvalidArgumentException
*/
private function getColor(ColorInterface $color)
{
if (!$color->isOpaque()) {
throw new InvalidArgumentException('Gmagick doesn\'t support transparency');
}
return new \GmagickPixel((string) $color);
}
/**
* Internal
*
* Get the mime type based on format.
*
* @param string $format
*
* @return string mime-type
*
* @throws InvalidArgumentException
*/
private function getMimeType($format)
{
static $mimeTypes = array(
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'wbmp' => 'image/vnd.wap.wbmp',
'xbm' => 'image/xbm',
);
if (!isset($mimeTypes[$format])) {
throw new InvalidArgumentException(sprintf('Unsupported format given. Only %s are supported, %s given', implode(", ", array_keys($mimeTypes)), $format));
}
return $mimeTypes[$format];
}
/**
* Sets colorspace and image type, assigns the palette.
*
* @param PaletteInterface $palette
*
* @throws InvalidArgumentException
*/
private function setColorspace(PaletteInterface $palette)
{
if (!isset(static::$colorspaceMapping[$palette->name()])) {
throw new InvalidArgumentException(sprintf('The palette %s is not supported by Gmagick driver', $palette->name()));
}
$this->gmagick->setimagecolorspace(static::$colorspaceMapping[$palette->name()]);
$this->palette = $palette;
}
}

View file

@ -0,0 +1,167 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Image\AbstractImagine;
use Imagine\Exception\NotSupportedException;
use Imagine\Image\BoxInterface;
use Imagine\Image\Metadata\MetadataBag;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\Palette\Grayscale;
use Imagine\Image\Palette\CMYK;
use Imagine\Image\Palette\RGB;
use Imagine\Image\Palette\Color\CMYK as CMYKColor;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Exception\RuntimeException;
/**
* Imagine implementation using the Gmagick PHP extension
*/
class Imagine extends AbstractImagine
{
/**
* @throws RuntimeException
*/
public function __construct()
{
if (!class_exists('Gmagick')) {
throw new RuntimeException('Gmagick not installed');
}
}
/**
* {@inheritdoc}
*/
public function open($path)
{
$path = $this->checkPath($path);
try {
$gmagick = new \Gmagick($path);
$image = new Image($gmagick, $this->createPalette($gmagick), $this->getMetadataReader()->readFile($path));
} catch (\GmagickException $e) {
throw new RuntimeException(sprintf('Unable to open image %s', $path), $e->getCode(), $e);
}
return $image;
}
/**
* {@inheritdoc}
*/
public function create(BoxInterface $size, ColorInterface $color = null)
{
$width = $size->getWidth();
$height = $size->getHeight();
$palette = null !== $color ? $color->getPalette() : new RGB();
$color = null !== $color ? $color : $palette->color('fff');
try {
$gmagick = new \Gmagick();
// Gmagick does not support creation of CMYK GmagickPixel
// see https://bugs.php.net/bug.php?id=64466
if ($color instanceof CMYKColor) {
$switchPalette = $palette;
$palette = new RGB();
$pixel = new \GmagickPixel($palette->color((string) $color));
} else {
$switchPalette = null;
$pixel = new \GmagickPixel((string) $color);
}
if ($color->getPalette()->supportsAlpha() && $color->getAlpha() < 100) {
throw new NotSupportedException('alpha transparency is not supported');
}
$gmagick->newimage($width, $height, $pixel->getcolor(false));
$gmagick->setimagecolorspace(\Gmagick::COLORSPACE_TRANSPARENT);
$gmagick->setimagebackgroundcolor($pixel);
$image = new Image($gmagick, $palette, new MetadataBag());
if ($switchPalette) {
$image->usePalette($switchPalette);
}
return $image;
} catch (\GmagickException $e) {
throw new RuntimeException('Could not create empty image', $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function load($string)
{
return $this->doLoad($string, $this->getMetadataReader()->readData($string));
}
/**
* {@inheritdoc}
*/
public function read($resource)
{
if (!is_resource($resource)) {
throw new InvalidArgumentException('Variable does not contain a stream resource');
}
$content = stream_get_contents($resource);
if (false === $content) {
throw new InvalidArgumentException('Couldn\'t read given resource');
}
return $this->doLoad($content, $this->getMetadataReader()->readStream($resource));
}
/**
* {@inheritdoc}
*/
public function font($file, $size, ColorInterface $color)
{
$gmagick = new \Gmagick();
$gmagick->newimage(1, 1, 'transparent');
return new Font($gmagick, $file, $size, $color);
}
private function createPalette(\Gmagick $gmagick)
{
switch ($gmagick->getimagecolorspace()) {
case \Gmagick::COLORSPACE_SRGB:
case \Gmagick::COLORSPACE_RGB:
return new RGB();
case \Gmagick::COLORSPACE_CMYK:
return new CMYK();
case \Gmagick::COLORSPACE_GRAY:
return new Grayscale();
default:
throw new NotSupportedException('Only RGB and CMYK colorspace are currently supported');
}
}
private function doLoad($content, MetadataBag $metadata)
{
try {
$gmagick = new \Gmagick();
$gmagick->readimageblob($content);
} catch (\GmagickException $e) {
throw new RuntimeException(
'Could not load image from string', $e->getCode(), $e
);
}
return new Image($gmagick, $this->createPalette($gmagick), $metadata);
}
}

View file

@ -0,0 +1,272 @@
<?php
/*
* This file is part of the Imagine package.
*
* (c) Bulat Shakirzyanov <mallluhuct@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Imagine\Gmagick;
use Imagine\Image\AbstractLayers;
use Imagine\Exception\RuntimeException;
use Imagine\Exception\NotSupportedException;
use Imagine\Exception\OutOfBoundsException;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Image\Metadata\MetadataBag;
use Imagine\Image\Palette\PaletteInterface;
class Layers extends AbstractLayers
{
/**
* @var Image
*/
private $image;
/**
* @var \Gmagick
*/
private $resource;
/**
* @var integer
*/
private $offset = 0;
/**
* @var array
*/
private $layers = array();
/**
* @var PaletteInterface
*/
private $palette;
public function __construct(Image $image, PaletteInterface $palette, \Gmagick $resource)
{
$this->image = $image;
$this->resource = $resource;
$this->palette = $palette;
}
/**
* {@inheritdoc}
*/
public function merge()
{
foreach ($this->layers as $offset => $image) {
try {
$this->resource->setimageindex($offset);
$this->resource->setimage($image->getGmagick());
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to substitute layer', $e->getCode(), $e);
}
}
}
/**
* {@inheritdoc}
*/
public function coalesce()
{
throw new NotSupportedException('Gmagick does not support coalescing');
}
/**
* {@inheritdoc}
*/
public function animate($format, $delay, $loops)
{
if ('gif' !== strtolower($format)) {
throw new NotSupportedException('Animated picture is currently only supported on gif');
}
if (!is_int($loops) || $loops < 0) {
throw new InvalidArgumentException('Loops must be a positive integer.');
}
if (null !== $delay && (!is_int($delay) || $delay < 0)) {
throw new InvalidArgumentException('Delay must be either null or a positive integer.');
}
try {
foreach ($this as $offset => $layer) {
$this->resource->setimageindex($offset);
$this->resource->setimageformat($format);
if (null !== $delay) {
$this->resource->setimagedelay($delay / 10);
}
$this->resource->setimageiterations($loops);
}
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to animate layers', $e->getCode(), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function current()
{
return $this->extractAt($this->offset);
}
/**
* Tries to extract layer at given offset
*
* @param integer $offset
* @return Image
* @throws RuntimeException
*/
private function extractAt($offset)
{
if (!isset($this->layers[$offset])) {
try {
$this->resource->setimageindex($offset);
$this->layers[$offset] = new Image($this->resource->getimage(), $this->palette, new MetadataBag());
} catch (\GmagickException $e) {
throw new RuntimeException(sprintf('Failed to extract layer %d', $offset), $e->getCode(), $e);
}
}
return $this->layers[$offset];
}
/**
* {@inheritdoc}
*/
public function key()
{
return $this->offset;
}
/**
* {@inheritdoc}
*/
public function next()
{
++$this->offset;
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->offset = 0;
}
/**
* {@inheritdoc}
*/
public function valid()
{
return $this->offset < count($this);
}
/**
* {@inheritdoc}
*/
public function count()
{
try {
return $this->resource->getnumberimages();
} catch (\GmagickException $e) {
throw new RuntimeException('Failed to count the number of layers', $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset)
{
return is_int($offset) && $offset >= 0 && $offset < count($this);
}
/**
* {@inheritdoc}
*/
public function offsetGet($offset)
{
return $this->extractAt($offset);
}
/**
* {@inheritdoc}
*/
public function offsetSet($offset, $image)
{
if (!$image instanceof Image) {
throw new InvalidArgumentException('Only a Gmagick Image can be used as layer');
}
if (null === $offset) {
$offset = count($this) - 1;
} else {
if (!is_int($offset)) {
throw new InvalidArgumentException('Invalid offset for layer, it must be an integer');
}
if (count($this) < $offset || 0 > $offset) {
throw new OutOfBoundsException(sprintf('Invalid offset for layer, it must be a value between 0 and %d, %d given', count($this), $offset));
}
if (isset($this[$offset])) {
unset($this[$offset]);
$offset = $offset - 1;
}
}
$frame = $image->getGmagick();
try {
if (count($this) > 0) {
$this->resource->setimageindex($offset);
$this->resource->nextimage();
}
$this->resource->addimage($frame);
/**
* ugly hack to bypass issue https://bugs.php.net/bug.php?id=64623
*/
if (count($this) == 2) {
$this->resource->setimageindex($offset+1);
$this->resource->nextimage();
$this->resource->addimage($frame);
unset($this[0]);
}
} catch (\GmagickException $e) {
throw new RuntimeException('Unable to set the layer', $e->getCode(), $e);
}
$this->layers = array();
}
/**
* {@inheritdoc}
*/
public function offsetUnset($offset)
{
try {
$this->extractAt($offset);
} catch (RuntimeException $e) {
return;
}
try {
$this->resource->setimageindex($offset);
$this->resource->removeimage();
} catch (\GmagickException $e) {
throw new RuntimeException('Unable to remove layer', $e->getCode(), $e);
}
}
}