Re-sizing image by width using php

A simple yet very useful function to re-size image by maximum width while keeping width and height in proportion. You just need to pass the maximum width allowed to this function and this function will return you an array containing new width and height.

For example, resize_image_by_width(“/var/www/mysite/images/imagename.jpg”, 200) would return array(‘w’=>200, ‘h’=>62.8787878788) to a 264×83 image.

function resize_image_by_width($image_loc, $maxwidth )	{

	if(!function_exists('getimagesize'))  { //if the useful getimagesize function is not available.
		return false; //do nothing
	}

	$size = getimagesize($image_loc); //get size array		
	if($size==null) return false;			
	$img_dim['w'] = $size[0]; //new image width which is in fact actual image width
	$img_dim['h'] = $size[1]; //new image height which is in fact actual image height
        $img_width = $size[0]; //actual width
        $img_height = $size[1]; //actual height
        $ratio = $img_width/$img_height; //aspect ratio
        if($img_width>$maxwidth) { //if actual width is larger than maximum allowed width
             $img_dim['w'] = $maxwidth; //set new width to maximum allowed width
             $img_dim['h'] = $img_dim['w']/$ratio; //and calculate new height and set
        }

        return $img_dim; //return in form of array('width'=>200, 'height'=>'whatever')
}

Note: Pass full absolute path to image as the first argument.

Leave a Reply

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