4

I want to do the following :

  • I need to resize images to fit and fill enterly 100x100 pixel box
    not all image are perfect squares, and thats my problem for this task
    1. I want to determine wich side (width or height) is the smallest.
    2. Bring that Side to 100px while scaling down; Center back
    3. Crop the overflow on both side

I've tried the width/height :100% technic but that doesnt give the result i want, (it is streched and ugly). Also i've seen some method but in C# ... I need in PHP.

I would appreciate any advice, directions, input, or ready script... Thanks

using PHP 5.3.0

james
  • 41
  • 1
  • 3
  • In step 2, don't you mean the smallest? If you bring the largest dimension down, you won't have to crop anything and the image will never completely fill the 100x100 container unless the original dimensions were equal. – Mike Aug 08 '11 at 18:10
  • I think he means set the larger of the sides to 100 while adjusting the other one to be some fraction of 100 pixels depending on aspect ratio. – Jeff Lambert Aug 08 '11 at 18:22
  • Here is how I do it in c#, just get the logic from it. See my answer to this post: http://stackoverflow.com/questions/18014365/c-sharp-crop-image-from-center/27164374#27164374 – h3n Nov 27 '14 at 06:38

1 Answers1

3

You must be able to calculate the aspect ratio by knowing the image dimensions beforehand. For more info, see getimagesize()

$width = 268;
$height = 300;
$MAX_SIZE = 100;
if($width > $MAX_SIZE || $height > $MAX_SIZE) {
    $aspect = $width / $height;
    if($width > $height) {
        $width = $MAX_SIZE;
        $height = intval($MAX_SIZE / $aspect);
    } else {
        $height = $MAX_SIZE;
        $width = intval($MAX_SIZE * $aspect);
    }
}

Afterwards, the scaled down height will be available in $height and the scaled down width will be available in $width.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96