更改Imagerotate的旋转中心

时间:2013-05-18 18:12:35

标签: php

Imagerotate使用给定角度(以度为单位)旋转图像。

旋转中心是图像的中心,旋转的图像可能与原始图像的尺寸不同。

如何更改旋转中心以协调x_new和y_new并避免自动调整大小?

示例:围绕红点旋转。

Example

2 个答案:

答案 0 :(得分:2)

想到的第一个想法是移动图像,使其新中心位于x_new,y_new旋转并向后移动。

假设:

0 < x_new < w
0 < y_new < h

伪代码:

new_canter_x = MAX(x_new, w - x_new)
new_center_y = MAX(y_new, h - y_new)

create new image (plain or transparent background):
width = new_canter_x * 2
height = new_center_y * 2

copy your old image to new one to coords:
new_center_x - x_new
new_center_y - y_new

imagerotate the new image.

现在你只需要切掉你感兴趣的部分。

答案 1 :(得分:0)

正确的方法是旋转,然后使用正确的转换参数进行裁剪。

另一种方法是移动,旋转然后再次移动(数学更简单,但代码更多)。

$ x和$ y是红点的坐标。

private function rotateImage($image, $x, $y, $angle)
{
    $widthOrig = imagesx($image);
    $heightOrig = imagesy($image);
    $rotatedImage = $this->createLayer($widthOrig * 2, $heightOrig * 2);
    imagecopyresampled($rotatedImage, $image, $widthOrig - $x, $heightOrig - $y, 0, 0, $widthOrig, $heightOrig, $widthOrig, $heightOrig);
    $rotatedImage = imagerotate($rotatedImage, $angle, imageColorAllocateAlpha($rotatedImage, 0, 0, 0, 127));
    $width = imagesx($rotatedImage);
    $height = imagesy($rotatedImage);
    $image = $this->createLayer();
    imagecopyresampled($image, $rotatedImage, 0, 0, $width / 2 - $x, $height / 2 - $y, $widthOrig, $heightOrig, $widthOrig, $heightOrig);
    return $image;
}

private function createLayer($width = 1080, $height = 1080)
{
    $image = imagecreatetruecolor($width, $height);
    $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
    imagefill($image, 0, 0, $color);
    return $image;
}