Fixing aspect-ratio of images in PHP

Frequently when you are displaying images on a page using a fixed width and height , the images come out stretched or squeezed. This is because the aspect ratio of the images have not been maintained. In such a case you can use the following script to correctly display the images according to the aspect-ratio of the image without actually resizing the image in a editor. This can be handy when you need to quickly correct image distortions. Here you need to keep either the width or the height fixed, so the other dimension can be calculated. Below the width is kept fixed at 200px, and the height is varied depending on the aspect ratio of the image, thus displaying the image without any distortion.

$imageFile = 'path/to/image';
/* Set the width fixed at 200px; */
$width = 200;
/* Get the image info */
$info = getimagesize($imageFile);
/* Calculate aspect ratio by dividing height by width */
$aspectRatio = $info[1] / $info[0];
/* Keep the width fix at 100px, 
   but change the height according to the aspect ratio */
$newHeight = (int)($aspectRatio * $width) . "px";
/* Use the 'newHeight' in the CSS height property below. */
$width .= "px";
echo "<img style=\"width: $width; height: $newHeight;\" 
       src=\"$imageFile\" />";

Read More