// angle in degrees, clockwise, allowed values from 0 to 360 degrees
function rotateImage ($image, $angle)
{
if ( ($angle < 0) || ($angle > 360) )
{
exit ("Error, angle passed out of range: [0,360]");
}
$width = imagesx ($image);
$height = imagesy ($image);
$dstImage = imagecreatetruecolor ($width, $height);
if ( ($angle == 0) || ($angle == 360) )
{
// Just copy image to output:
imagecopy ($dstImage, $image, 0, 0, 0, 0, $width, $height);
}
else
{
$centerX = floor ($width / 2);
$centerY = floor ($height / 2);
// Run on all pixels of the destination image and fill them:
for ($dstImageX = 0; $dstImageX < $width; $dstImageX++)
{
for ($dstImageY = 0; $dstImageY < $height; $dstImageY++)
{
// Calculate pixel coordinate in coordinate system centered at the image center:
$x = $dstImageX - $centerX;
$y = $centerY - $dstImageY;
if ( ($x == 0) && ($y == 0) )
{
// We are in the image center, this pixel should be copied as is:
$srcImageX = $x;
$srcImageY = $y;
}
else
{
$r = sqrt ($x * $x + $y * $y); // radius - absolute distance of the current point from image center
$curAngle = asin ($y / $r); // angle of the current point [rad]
if ($x < 0)
{
$curAngle = pi () - $curAngle;
}
$newAngle = $curAngle + $angle * pi () / 180; // new angle [rad]
// Calculate new point coordinates (after rotation) in coordinate system at image center
$newXRel = floor ($r * cos ($newAngle));
$newYRel = floor ($r * sin ($newAngle));
// Convert to image absolute coordinates
$srcImageX = $newXRel + $centerX;
$srcImageY = $centerY - $newYRel;
}
$pixelColor = imagecolorat ($image, $srcImageX, $srcImageY); // get source pixel color
imagesetpixel ($dstImage, $dstImageX, $dstImageY, $pixelColor); // write destination pixel
}
}
}
return $dstImage;
}