How to read and write images

Functions that work with images

Name Description
imagecreatefromxxx($path) Creates an image of the xxx type from the specified file path.
imagesx($image) Returns the width of the specified image.
imagesy($image) Returns the height of the specified image.
imagexxx($image, $path) Writes the specified image of the xxx type to the specified file path.
imagedestroy($image) Frees any memory that’s used for the specified image.

Code that reads and writes an image

      // Set the paths for the images
      $image_path = getcwd() . DIRECTORY_SEPARATOR . 'gibson_sg.png'; 
      $image_path_2 = getcwd() . DIRECTORY_SEPARATOR . 'gibson_sg_2.png';

      // Get the image width, height, and type 
      $image_info = getimagesize($image_path); 
      $image_type = $image_info[2]; 
      
      // Set up the function names for the image type 
      switch($image_type) {
        case IMAGETYPE_JPEG: 
          $image_from_file = 'imagecreatefromjpeg';
          $image_to_file = 'imagejpeg'; 
          break; 
        case IMAGETYPE_GIF:
          $image_from_file = 'imagecreatefromgif';
          $image_to_file = 'imagegif';
          break; 
        case IMAGETYPE_PNG:
          $image_from_file = 'imagecreatefrompng';
          $image_to_file = 'imagepng';
          break; 
        default: 
          echo("File must be a JPEG, GIF, or PNG image.<br>"); 
          exit; 
      }
      
      // Create a new image from the file 
      $image = $image_from_file($image_path); 
      
      // Check the image's width and height 
      $image_width = imagesx($image); 
      $image_height = imagesy($image); 
      
      // Write the image to a file 
      $image_to_file($image, $image_path_2); 
      
      // Free any memory associated with the image 
      imagedestroy($image);

Back