This is a short and simple guide on how to convert a portrait image into a landscape image using PHP’s GD and Image Functions.
Take a look at the following code snippet:
<?php //The location of our image / photograph. $imgFile = 'img.jpg'; //Get the width and height of our image in pixels. list($width, $height) = getimagesize($imgFile); //If the height is larger than the width, assume //that it is a portrait photograph. if($height > $width){ //Create an image from our original JPEG image. $sourceCopy = imagecreatefromjpeg($imgFile); //Rotate this image by 90 degrees. $rotatedImg = imagerotate($sourceCopy, 90, 0); //Replace original image with rotated / landscape version. imagejpeg($rotatedImg, $imgFile); }
An explanation of the example above:
- We assigned the file path of our image to a PHP variable called $imgFile.
- We got the width and height of the image in pixels by using the function getimagesize. This function returns an array, with the width (px) at index 0 and the height (px) at index 1. We used the language construct list to quickly assign these two array elements to the variables $width and $height.
- In our IF statement, we check to see if the height of the image is larger than the width of the image. If the height is larger than the width, then we assume that it is a portrait photograph.
- Inside our IF statement, we create a copy of our JPEG file using the function imagecreatefromjpeg.
- We then rotate the copy by 90 degrees using the PHP function imagerotate.
- Finally, we overwrite our original image with the new rotated version by using the function imagejpeg.
NOTE: If your source image is a PNG file, then you may want to use the functions imagecreatefrompng and imagepng instead.