views:

299

answers:

2

I'm looking for help/suggestions in finding the most efficient way to resize an image to be as small as possible using PHP/GD while preserving the aspect ratio of the original image but ensuring the the resized image is bigger than a defined minimum width & height.

For example, the resized image must have a width >= 400 and a height >= 300 but should be as close to those dimensions as possible while maintaining the original aspect ratio.

Such that a "landscape" image would have an ideal height of 300 or slightly larger with a width >= 400 and a "portrait" image would have an ideal width of 400 or slightly larger with a height >= 300.

A: 

This seems to get the job done...

    $data = @getimagesize($image);

    $o_w = $data[0];
    $o_h = $data[1];
    $m_w = 400;
    $m_h = 300;

    $c_w = $m_w / $o_w;
    $c_h = $m_h / $o_h;

    if($o_w == $o_h){
            $n_w = ($n_w >= $n_h)?$n_w:$n_h;
            $n_h = $n_w;
    } else {
            if( $c_w > $c_h ) {
                $n_w = $m_w;
                $n_h = $o_h * ($n_w/$o_w);
            } else {
                $n_h = $m_h;
                $n_w = $o_w * ($n_h/$o_h);
            }
    }
AutomaticDrone
A: 

I believe this is what you're looking for; specifically, the pictures in the middle column:

When source image is wider When source image is taller When aspect ratios are same

Following code is derived from Crop-To-Fit an Image Using ASP/PHP:

list(
  $source_image_width,
  $source_image_height
) = getimagesize( '/path/to/image' );

$target_image_width  = 400;
$target_image_height = 300;

$source_aspect_ratio = $source_image_width / $source_image_height;
$target_aspect_ratio = $target_image_width / $target_image_height;

if ( $target_aspect_ratio > $source_aspect_ratio )
{
  // if target is wider compared to source then
  // we retain ideal width and constrain height
  $target_image_height = ( int ) ( $target_image_width / $source_aspect_ratio );
}
else
{
  // if target is taller (or has same aspect-ratio) compared to source then
  // we retain ideal height and constrain width
  $target_image_width = ( int ) ( $target_image_height * $source_aspect_ratio );
}

// from here, use GD library functions to resize the image
Salman A