PHP image rotation is one of the features of PHP that we can use the built-in imagerotate() function to rotate images according to the given angle. This function rotates the image from the center by the angle given in its parameter.
resource imagerotate( $image, $angle, $bgd_color, $ignore_transparent = 0 )
Parameters: This function accepts four parameters as mentioned above and described below:
- $image: It is returned by one of the image creation functions, such as
imagecreatetruecolor()
. It is used to create the size of the image. - $angle: This parameter holds the rotation angle in degrees. The rotation angle is used to rotate an image in the anticlockwise direction.
- $bgd_color: This parameter holds the background color of the uncovered zone after rotation.
- $ignore_transparent: If this parameter is set and non-zero then transparent colors are ignored.
Return Value: This function returns an image resource for the rotated image on success or False on failure.
For image rotation in PHP, there is a class called Imagick, which you can also use, but this class needs to be installed, which some hosts and servers do not install, that’s why in this tutorial, we only use the built-in function. We will use PHP.
PNG image rotation
$image_name ='img.png';
$image = imagecreatefrompng($image_name);
$img = imagerotate($image, 45, 0);
imagepng($img,"rotated_img.png");
In this example, we get the picture in PNG format and after rotating it by 45 degrees, we save it in rotated_img.png. Because this picture is PNG, after rotation, it will have a background, and the background color will be black.
As you can see, it is easy to rotate images using the imagerotate()
function in PHP.
PHP JPEG image rotation
To rotate images in JPEG format, we do not change the imagerotate()
function and only change other required functions.
$image_name ='img.jpg';
$image = imagecreatefromjpeg($image_name);
$img = imagerotate($image, 45, 0);
imagejpeg($img,"rotated_img.jpg");
WebP image rotation
The WebP format is one of the image formats designed by Google and, like SVG, is known as Next-Gen Image. The size of WebP images is lower than JPEG and PNG because this format uses text to store images.
$image_name ='img.webp';
$image = imagecreatefromwebp($image_name);
$img = imagerotate($image, 45, 0);
imagewebp($img,"rotated_img.webp");