Imagick:在Imagick项目上设置重力

时间:2011-04-28 15:06:00

标签: php imagemagick imagick

我在Imagick设置图像的重力方面遇到了一些实际困难。

我已设法设置ImaickDraw对象的重力,但我没有成功在Imagick对象中设置它。

下面是我正在使用的基本代码。我刚刚和ImagickDraw使用相同,但显然它不起作用。

$rating = new Imagick("ratings/" . $rating . ".png");
$rating->setGravity (Imagick::GRAVITY_SOUTH);
$im->compositeImage($rating, imagick::COMPOSITE_OVER, 20, 20); 

如何为现有图像而不是绘图对象设置重力?

谢谢!

1 个答案:

答案 0 :(得分:3)

在您的情况下,setGravity方法应该应用于$im对象。但无论如何,看起来重力只影响使用drawImage插入的ImagickDraw对象,并且无法像使用ImageMagick命令那样将图像放入绘图中。

所以有两种方法可以做到这一点:

第一。如果您的托管允许函数shell_execexec,则可以运行类似。

的命令
convert image.jpg -gravity south -\
  draw "image Over 0,0 0,0 watermak.png" \
  result.jpg`

第二。否则,您可以计算放置在基本图像上的图像的位置,并使用compositeImage

$imageHight = $im->getImageHeight();
$imageWith = $im->getImageWidth();

// Scale the sprite if needed.
// Here I scale it to have a 1/2 of base image's width
$rating->scaleImage($imageWith / 2, 0);

$spriteWidth = $rating->getImageWidth();
$spriteHeight = $rating->getImageHeight();

// Calculate coordinates of top left corner of the sprite 
// inside of the image
$left = ($imageWidth - $spriteWidth)/2; // do not bother to round() values, IM will do that for you
$top = $imageHeight - $spriteHeight;

// If you need bottom offset to be, say, 1/6 of base image height,
// then decrease $top by it. I recommend to avoid absolute values here
$top -= $imageHeight / 6;

$im->compositeImages($rating, imagick::COMPOSITE_OVER, $left, $top);