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.
Possibly Related posts:
- Drupal “disk quota per user has been reached” settings
When a certain number of uploads is reached Drupal would show errors, something like this: “The selected file cannot be attached to this post, because... - Auto linking text string having image tags using Text Helper in CakePHP
Recently I found that auto linking urls and emails of a string having image tags within was not possible using text helper in CakePHP. It... - A simple javascript image slide show using setTimeout and jQuery
Just now i created a small slideshow. The slideshow uses some static images stored in a javascript object (array) and runs till the last image... - Gimp Image Editor not launching in KUbuntu – resolved
I recently had installed Gimp image editor in my KUbuntu through software management interface. After the installation was done i clicked the Gimp icon to...
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.





