Created
June 27, 2013 06:08
-
-
Save t-cyrill/5874310 to your computer and use it in GitHub Desktop.
PHP imagick wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ImagickFilter { | |
private $imagick; | |
private function __construct($imagick) | |
{ | |
$this->imagick = clone $imagick; | |
$this->imagick->profileImage('*', null); | |
} | |
public static function factoryByFile($path) | |
{ | |
$imagick = new Imagick($path); | |
$instance = new self($imagick); | |
$imagick->destroy(); | |
return $instance; | |
} | |
public static function factoryByImagick($imagick) | |
{ | |
return new self($imagick); | |
} | |
public function getImageSize() | |
{ | |
$imagick = $this->imagick; | |
$imagick->setFirstIterator(); | |
$page = $imagick->getImagePage(); | |
$size = $imagick->getImageGeometry(); | |
if ($page['width'] * $page['height'] > $size['width'] * $size['height']) { | |
$size = $page; | |
} | |
return $size; | |
} | |
/** | |
* 背景を決めて非透過処理を行う | |
* | |
* @param string $background [=#ffffff] #ffffffのようなImagickPixelが解釈可能な色を表す文字列 | |
*/ | |
public function nonTransparent($background = '#ffffff') | |
{ | |
$size = $this->getImageSize(); | |
$base = $this->imagick->getImage(); | |
$base->newImage($size['width'], $size['height'], new \ImagickPixel($background)); | |
$base->compositeImage($this->imagick, \Imagick::COMPOSITE_DEFAULT, 0, 0, \Imagick::CHANNEL_ALL); | |
$this->imagick->destroy(); | |
$this->imagick = $base; | |
} | |
public function toJpeg($quality = 100) | |
{ | |
$this->imagick->setImageFormat('JPEG'); | |
$this->imagick->setImageCompressionQuality($quality); | |
} | |
public function writeImageFile($filepath) | |
{ | |
return file_put_contents($filepath, $this->imagick->getImageBlob(), LOCK_EX); | |
} | |
public function getImagick() | |
{ | |
return $this->imagick; | |
} | |
} | |
// | |
if (debug_backtrace() === array()) { | |
$filter = ImagickFilter::factoryByFile($tempfile); | |
$filter->nonTransparent() | |
->cropImage($px, $py, $wx, $wy) | |
->toJpeg() | |
->writeImageFile('/tmp/test.jpg'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment