Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image without distortion keeping aspect ratio then crop excess using WideImage

I have an area on a site that I am working on that will display a users profile image that is pulled from an external source (therefore no control on its original size).

What I am looking to do is take an image (in this example 1000px x 800px and resize it to 200px x 150px. Obviously with this there is an aspect ratio difference.

What I want to do is resize the original image without distortion, which in this case would produce a 200px x 160px image. What I then want to do is crop any excess from the edges to produce the correct image size. So in this case crop 5px off the top and bottom of the image finally producing a 200px x 150px.

I have the WideImage library currently and would like to use that. I have seen several similar questions on SO but nothing that I can say exactly does as I am trying to achieve.

like image 281
lethalMango Avatar asked Jun 15 '11 09:06

lethalMango


1 Answers

I tried all of your solutions and came up with strange numbers every time. So, this is my way of doing the calculations.

Basic proportional formula: a/b=x/y -> ay = bx then solve for the unknown value. So, let's put this into code.

This function assumes you've opened the image into a variable. If you pass the path you'll have to open the image in the function, do the math, kill it, return the values and then open the image again when you resize it, that's inefficient...

function resize_values($image){
    #for the purpose of this example, we'll set this here
    #to make this function more powerful, i'd pass these 
    #to the function on the fly
    $maxWidth = 200; 
    $maxHeight = 200;

    #get the size of the image you're resizing.
    $origHeight = imagesy($image);
    $origWidth = imagesx($image);

    #check for longest side, we'll be seeing that to the max value above
    if($origHeight > $origWidth){ #if height is more than width
         $newWidth = ($maxHeight * $origWidth) / $origHeight;

         $retval = array(width => $newWidth, height => $maxHeight);
    }else{
         $newHeight= ($maxWidth * $origHeight) / $origWidth;

         $retval = array(width => $maxWidth, height => $newHeight);
    }
return $retval;
}

Above function returns an array, obviously. You can work the formula into whatever script you're working on. This has proven to be the right formula for the job. So... up to you whether or not you use it. LATER!

like image 95
Chad A Avatar answered Oct 06 '22 00:10

Chad A