Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolew1/4074ce32945277b0fe0db85982a28509 to your computer and use it in GitHub Desktop.
Save tolew1/4074ce32945277b0fe0db85982a28509 to your computer and use it in GitHub Desktop.
Manual Imagick crop via gravity
<?php
$this->imgMetadata['format'] = strtolower($this->imagickObj->getImageFormat());
$this->imgMetadata['width'] = $this->imagickObj->getImageWidth();
$this->imgMetadata['height'] = $this->imagickObj->getImageHeight();
$x = $y = 0;
switch ($gravity) {
case 'center':
// $gravity = \Imagick::GRAVITY_CENTER;
$x = ($this->imgMetadata['width']/2) - ($width/2);
$y = $this->imgMetadata['height']/2 - ($height/2);
break;
case 'northwest':
// $gravity = \Imagick::GRAVITY_NORTHWEST;
break;
case 'north':
// $gravity = \Imagick::GRAVITY_NORTH;
$x = ($this->imgMetadata['width']/2) - ($width/2);
break;
case 'northeast':
// $gravity = \Imagick::GRAVITY_NORTHEAST;
$x = ($this->imgMetadata['width']) - $width;
break;
case 'west':
// $gravity = \Imagick::GRAVITY_WEST;
$y = ($this->imgMetadata['height']/2) - ($height/2);
break;
case 'east':
// $gravity = \Imagick::GRAVITY_EAST;
$x = $this->imgMetadata['width']- $width;
$y = ($this->imgMetadata['height']/2) - ($height/2);
break;
case 'southwest':
// $gravity = \Imagick::GRAVITY_SOUTHWEST;
$x = 0;
$y = $this->imgMetadata['height'] - $height;
break;
case 'south':
// $gravity = \Imagick::GRAVITY_SOUTH;
$x = ($this->imgMetadata['width']/2) - ($width/2);
$y = $this->imgMetadata['height'] - $height;
break;
case 'southeast':
// $gravity = \Imagick::GRAVITY_SOUTHEAST;
$x = $this->imgMetadata['width'] - $width;
$y = $this->imgMetadata['height'] - $height;
break;
default:
//throw something
break;
}
if('gif'!=$this->imgMetadata['format']){
//gravity does not work with crop
// $this->imagickObj->setGravity($gravity);
$this->imagickObj->setImageCompressionQuality($quality);
$this->imagickObj->cropImage($width,$height,$x,$y);
}
else {
foreach ($this->imagickObj as $frame) {
//gravity does not work with crop
// $this->imagickObj->setGravity($gravity);
$frame->setImageCompressionQuality($quality);
$frame->cropImage($width,$height,$x,$y);
// $frame->setImagePage($width, $height, 0, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment