How to resize an image

Functions that can resize an image

Name Description
imagecreatetruecolor($w, $h) Returns an all-black truecolor image of the specified size.
imagecopyresampled($di, $si, $dx, $dy, $sx, $sy, $dw, $dh, $sw, $sh) Copies a rectangular portion of the source image (s) to the destination image (d), resizing the image if necessary.

Code that resizes an image to a 100 by 100 pixel maximum

      // Set some variables 
      $old_path = getcwd() . DIRECTORY_SEPARATOR . 'gibson_sg.png'; 
      $new_path = getcwd() . DIRECTORY_SEPARATOR . 'gibson_sg_100.png'; 
      $image_type = IMAGETYPE_PNG; 
      
      // Get the old image and its height and width 
      $old_image = imagecreatefrompng($old_path); 
      $old_width = imagesx($old_image); 
      $old_height = imagesy($old_image); 
      
      // Calculate height and width ratios for a 100x100 pixel maximum
      $width_ratio = $old_width / 100; 
      $height_ratio = $old_height / 100; 
      
      // If image is larger than specified ratio, create the new image 
      if ($width_ratio > 1 || $height_ratio > 1) {
        // Calculate height and width for the new image 
        $ratio = max($width_ratio, $height_ratio); 
        $new_height = round($old_height / $ratio);
        $new_width = round($old_width / $ratio); 
        
        // Create the new image 
        $new_image = imagecreatetruecolor($new_width, $new_height); 
        
        // Copy old image to new image to resize the file 
        $new_x = 0; // Start new image in upper left corner
        $new_y = 0;
        $old_x = 0;
        $old_y = 0; // Copy old image from upper left corner
        imagecopyresampled($new_image, $old_image, 
                           $new_x, $new_y, $old_x, $old_y, 
                           $new_width, $new_height, $old_width, $old_height); 
        
        // Write the new image to a file 
        imagepng($new_image, $new_path); 
        
        // Free any memory associated with the new image 
        imagedestroy($new_image);
      } 
      
      // Free any memory associated with the old image 
      imagedestroy($old_image);

Back