Constraining an Image to a Maximum Width using ImageMagick and PHP

Category: Software and Systems Engineering
Author: Sean O'Donnell
Thu, Feb. 20th, 2003 @ 2:20:22 (MST)

This example shows how to resize and constrain an image file to a desired maximum width.

<?php
/**
* resize_constrained_width($path_convert,$file_path,$file_max_width)
* resize an image and constrain the height to the maximum width
*/
class image_magick {
    function 
resize_constrained_width($path_convert,$file_path,$file_max_width) {
        
$int_imgsize getimagesize($file_path);
        if (
$int_imgsize[0] > $file_max_width) {
            
/**
            * resize photo to fit interface restrictions (constrained by width)
            */
            
exec($path_convert ." -geometry "$file_max_width ." "$file_path ." "$file_path);
            return;
        } else {
            
/**
            * image is smaller than the maximum width
            */
            
return;
        }
    }
}

/**
* define the path to the ImageMagick convert utility
* (using a constant instead of a variable)
*/
define("PATH_CONVERT","/usr/bin/convert");

/**
* set the physical path to the file (example)
*/
$file_path_physical "/home/myusername/public_html/images/flag_ireland.gif";

/**
* set the Maximum Width
*/
$file_max_width 225;

/**
* execute the function
*/
image_magick::resize_constrained_width(PATH_CONVERT,$file_path_physical,$file_max_width);

/** done, the image is now resized */
?>

The example above will resize the Image "/home/myusername/public_html/images/example.gif" to a width of 225, if the image's original width is not smaller.

You must also ensure proper user ownership and read/write permissions of the image/file.

Copyleft (<) 1998-2019 www.seanodonnell.com