Change the center of rotation of Imagerotate

Imagerotate rotates the image using the specified angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different sizes than the original image.

How to change the center of rotation to x_new and y_new coordinates and avoid automatic resizing?

Example: rotation around a red dot.

Example

+4
source share
2 answers

The first idea that comes to mind is to move the image so that its new center is at x_new, y_new rotates it and moves backward.

assumptions:

0 < x_new < w 0 < y_new < h 

pseudo code:

 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. 

now you just need to cut out the part that interests you.

+2
source

The right way to do this is to rotate and then crop using the correct transformation options.

Another way is moving, rotating, then moving again (simpler math, but more code).

$ x and $ y are the coordinates of the red dot.

 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; } 
0
source

Source: https://habr.com/ru/post/1481546/


All Articles