Simple Image Resizing in PHP
Simple Image Resizing in PHP

Image resizing in one of the problem that every developer must have face. Resizing of the images need to take care or they will get distorted, and it will give a bad impression on your users. One solution can be there, we can create same image with different size. This is a good idea, but is also have some drawbacks. If an image is used at many different places, then there will be alot of duplicate image, which will consume space unknowingly. So to solve this problem I have come at an idea of using the same image but resizing it dynamically to maintain the aspect ratio.


My idea really simple, I will create a function that takes the image, and the required width of the image needed, and the height will be automatically generated which will maintain the aspect ratio. This function will return the image as the output.


Resize Function


function imgResize($img, $req_width){
  $img_size = getimagesize($img);
  $width = $img_size[0];
  $height = $img_size[1];

  if($width > $height){
    $p = ($req_width / $width);
    $p = ($req_width / $height);

  $width = round($width * $p);
  $height = round($height * $p);

  $new_image = '<img src="'.$img.'" width="'.$width.'" height="'.$height.'" />';
  return $new_image;


Display the Image


  $img = "blank.png";
  $new_img = imgResize($img, 500);
  echo $new_img;

Leave a Reply

Your email address will not be published. Required fields are marked *