PHP Image Resize to a specific height and width

Discussion in 'PHP' started by audax, Oct 26, 2006.

  1. #1
    Hello!

    As the title states, I'm trying to use PHP to resize larger images into smaller ones with a specific height AND width.
    The codes/tutorials/examples I've found resize it to a specific width then have the height dynamic as to match the aspect ratio. What I'm trying to do is make a way so that the image will be resized to the predefined measurements while keeping the aspect ratio to maintain good quality. If the aspect ratio, when shrunk, does not match the size of the thumbnail image, the PHP would (I assume) trim off the excess so that the quality wouldn't be stretched or skewed (if that makes sense.) I've seen it done with ASP - not the actual source code though - and am trying to make it in PHP.

    If that doesn't make sense, let me put it this way. Let's say I have a collection of images, some being 434x640 and others 450x619. I want the images all to be scaled down to 160x204 - no bigger, no smaller - but not distorted. If maintaining the aspect ratio means trimming a little off the sides, then so-be-it. Is it possible in PHP to do so? Or is there a better way than manually creating the images?

    Thanks in advance for any responses whatsoever :)
     
    audax, Oct 26, 2006 IP
  2. javo

    javo Peon

    Messages:
    7
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    i can't say it is functionally for 100% but try it

    
    
    $file = 'test.jpg';          
    $newwidth = '300';      
    $newheight = '200';   
    
    header('Content-type: image/jpeg');
    list($width, $height) = getimagesize($file);
    $input = imagecreatefromjpeg($file);
    imagecopyresized($output, $input, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    imagejpeg($output);
     
    PHP:
     
    javo, Oct 27, 2006 IP
    streety likes this.
  3. streety

    streety Peon

    Messages:
    321
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Looks like a good little script javo.

    Because quality is a concern here it may be worth setting the quality argument for imagejpeg to 100. I also assume you want to save these images rather than create them dynamically each time so you'll also want to provide a filename to imagejpeg. All the details are on the php site.

    Should also be possible to do something similar for other file formats.
     
    streety, Oct 27, 2006 IP