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.

<?php
 
$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\" />";

2 thoughts on “Fixing aspect-ratio of images in PHP

  1. This is truly helpful, and really easy to use.

    I re wrote some of the code to make things a little more optional:


    function image_fix($path,$pixelsize,$w_h,$css,$alt,$reload)
    {
    //path (after server name),height or width pxs(do not add "px"), h or w property(use "h" or "w")
    //,css apply as usual, realod (true, false)force reload

    $time = date("H:i:s");
    $imageFile = "http://".$_SERVER['SERVER_NAME']."/".$path;
    echo $imageFile;
    /* Set the width or height fixed */
    if($w_h=="h"){$newHeight=$pixelsize;}else{$width = $pixelsize;}
    /* Get the image info */
    $info = getimagesize($imageFile);

    /* Calculate aspect ratio by dividing height by width, or visa versa*/
    $aspectRatio = $info[1] / $info[0];

    /* Keep the width or height fix at 100,
    but change the other value according to the aspect ratio */
    if($w_h=="h"){$width = (int)($aspectRatio * $newHeight) . "px";$newHeight .='px';}else{$newHeight = (int)($aspectRatio * $width) . "px";$width .= "px";}

    /* Use the 'newHeight' in the CSS height property below. */
    //reload is true the force no catch on image
    if($reload){$imageFile .="?".$time;}else{$imageFile .="";}
    return "";
    }

    many many thanks

Comments are closed.