Index: modules/system/image.gd.inc
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/image.gd.inc,v
retrieving revision 1.3
diff -u -r1.3 image.gd.inc
--- modules/system/image.gd.inc	30 Dec 2008 16:43:19 -0000	1.3
+++ modules/system/image.gd.inc	13 Feb 2009 00:23:18 -0000
@@ -15,7 +15,10 @@
  * Retrieve information about the toolkit.
  */
 function image_gd_info() {
-  return array('name' => 'gd', 'title' => t('GD2 image manipulation toolkit'));
+  return array(
+    'name' => 'gd',
+    'title' => t('GD2 image manipulation toolkit'),
+  );
 }
 
 /**
@@ -76,144 +79,168 @@
 
 /**
  * Scale an image to the specified size using GD.
+ *
+ * @param $image
+ *   An image object. The $image->res, $image->width, and $image->height values
+ *   will be modified by this call.
+ * @param $width
+ *   The new width of the resized image in pixels.
+ * @param $height
+ *   The new height of the resized image in pixels.
  */
-function image_gd_resize($source, $destination, $width, $height) {
-  if (!file_exists($source)) {
-    return FALSE;
-  }
 
-  $info = image_get_info($source);
-  if (!$info) {
-    return FALSE;
-  }
+function image_gd_resize(&$image, $width, $height) {
+  $res = image_gd_create_tmp($image, $width, $height);
 
-  $im = image_gd_open($source, $info['extension']);
-  if (!$im) {
+  if (!imagecopyresampled($res, $image->res, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) {
     return FALSE;
   }
 
-  $res = imagecreatetruecolor($width, $height);
-  if ($info['extension'] == 'png') {
-    $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
-    imagealphablending($res, FALSE);
-    imagefilledrectangle($res, 0, 0, $width, $height, $transparency);
-    imagealphablending($res, TRUE);
-    imagesavealpha($res, TRUE);
-  }
-  elseif ($info['extension'] == 'gif') {
-    // If we have a specific transparent color.
-    $transparency_index = imagecolortransparent($im);
-    if ($transparency_index >= 0) {
-      // Get the original image's transparent color's RGB values.
-      $transparent_color = imagecolorsforindex($im, $transparency_index);
-      // Allocate the same color in the new image resource.
-      $transparency_index = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
-      // Completely fill the background of the new image with allocated color.
-      imagefill($res, 0, 0, $transparency_index);
-      // Set the background color for new image to transparent.
-      imagecolortransparent($res, $transparency_index);
-      // Find number of colors in the images palette.
-      $number_colors = imagecolorstotal($im);
-      // Convert from true color to palette to fix transparency issues.
-      imagetruecolortopalette($res, TRUE, $number_colors);
-    }
-  }
-  imagecopyresampled($res, $im, 0, 0, 0, 0, $width, $height, $info['width'], $info['height']);
-  $result = image_gd_close($res, $destination, $info['extension']);
-
-  imagedestroy($res);
-  imagedestroy($im);
-
-  return $result;
+  imagedestroy($image->res);
+  // Update image object.
+  $image->res = $res;
+  $image->info['width'] = $width;
+  $image->info['height'] = $height;
+  return TRUE;
 }
 
 /**
  * Rotate an image the given number of degrees.
- */
-function image_gd_rotate($source, $destination, $degrees, $background = 0x000000) {
-  if (!function_exists('imageRotate')) {
-    return FALSE;
-  }
-
-  $info = image_get_info($source);
-  if (!$info) {
-    return FALSE;
-  }
-
-  $im = image_gd_open($source, $info['extension']);
-  if (!$im) {
-    return FALSE;
-  }
-
-  $res = imageRotate($im, $degrees, $background);
-  $result = image_gd_close($res, $destination, $info['extension']);
-
-  return $result;
+ *
+ * @param $image
+ *   An image object. The $image->res value will be modified by this call.
+ * @param $degress
+ *   The number of degrees to rotate the image.
+ * @param $bgcolor
+ *   The color of the exposed background when rotating.
+ */
+function image_gd_rotate(&$image, $degrees, $bgcolor) {
+  $res = imagerotate($image->res, 360 - $degrees, $bgcolor);
+  imagedestroy($image->res);
+  $image->res = $res;
+  return TRUE;
 }
 
 /**
  * Crop an image using the GD toolkit.
+ *
+ * @param $image
+ *   An image object. The $image->res, $image->width, and $image->height values
+ *   will be modified by this call.
+ * @param $x
+ *   The starting x offset in pixels at which to start the crop.
+ * @param $y
+ *   The starting y offset in pixels at which to start the crop.
+ * @param $width
+ *   The width of the cropped area in pixels.
+ * @param $height
+ *   The height of the cropped area in pixels.
  */
-function image_gd_crop($source, $destination, $x, $y, $width, $height) {
-  $info = image_get_info($source);
-  if (!$info) {
+function image_gd_crop(&$image, $x, $y, $width, $height) {
+  $res = image_gd_create_tmp($image, $width, $height);
+
+  if (!imagecopyresampled($res, $image->res, 0, 0, $x, $y, $width, $height, $width, $height)) {
     return FALSE;
   }
 
-  $im = image_gd_open($source, $info['extension']);
-  $res = imageCreateTrueColor($width, $height);
-  imageCopy($res, $im, 0, 0, $x, $y, $width, $height);
-  $result = image_gd_close($res, $destination, $info['extension']);
-
-  imageDestroy($res);
-  imageDestroy($im);
+  // Destroy the original image and return the modified image.
+  imagedestroy($image->res);
+  $image->res = $res;
+  $image->info['width'] = $width;
+  $image->info['height'] = $height;
+  return TRUE;
+}
 
-  return $result;
+/**
+ * Convert an image resource to grayscale.
+ *
+ * @param $image
+ *   An image object. The $image->res value will be modified by this call.
+ */
+function image_gd_desaturate(&$image) {
+  return imagefilter($image->res, IMG_FILTER_GRAYSCALE);
 }
 
 /**
  * GD helper function to create an image resource from a file.
  *
- * @param $file
- *   A string file path where the image should be saved.
- * @param $extension
- *   A string containing one of the following extensions: gif, jpg, jpeg, png.
+ * @param $image
+ *   An image object. The $image->res value will populated by this call.
  * @return
- *   An image resource, or FALSE on error.
+ *   The image object with an image resource added.
+ * @see image_open()
  */
-function image_gd_open($file, $extension) {
-  $extension = str_replace('jpg', 'jpeg', $extension);
-  $open_func = 'imageCreateFrom' . $extension;
-  if (!function_exists($open_func)) {
-    return FALSE;
+function image_gd_open($image) {
+  $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
+  $open_func = 'imagecreatefrom'. $extension;
+
+  if (function_exists($open_func) && $image->res = $open_func($image->source)) {
+    return $image;
   }
-  return $open_func($file);
+  return FALSE;
 }
 
 /**
  * GD helper to write an image resource to a destination file.
  *
- * @param $res
- *   An image resource created with image_gd_open().
+ * @param $image
+ *   An image object.
  * @param $destination
  *   A string file path where the image should be saved.
  * @param $extension
  *   A string containing one of the following extensions: gif, jpg, jpeg, png.
  * @return
  *   Boolean indicating success.
+ * @see image_close()
  */
-function image_gd_close($res, $destination, $extension) {
-  $extension = str_replace('jpg', 'jpeg', $extension);
-  $close_func = 'image' . $extension;
+function image_gd_close($image, $destination) {
+  $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
+  $close_func = 'image'. $extension;
   if (!function_exists($close_func)) {
     return FALSE;
   }
   if ($extension == 'jpeg') {
-    return $close_func($res, $destination, variable_get('image_jpeg_quality', 75));
+    return $close_func($image->res, $destination, variable_get('image_jpeg_quality', 75));
   }
   else {
-    return $close_func($res, $destination);
+    return $close_func($image->res, $destination);
+  }
+}
+
+/**
+ * Create a true color image preserving transparency from a provided image.
+ */
+function image_gd_create_tmp($image, $width, $height) {
+  $res = imagecreatetruecolor($width, $height);
+
+  if ($image->info['extension'] == 'gif' || $image->info['extension'] == 'jpg') {
+    // Grab transparent color index from image resource.
+    $transparent = imagecolortransparent($image->res);
+
+    // If using indexed transparency, preserve it.
+    if ($transparent >= 0) {
+      // Get color(r,g,b) for index,.
+      $transparent = imagecolorsforindex($image->res, $transparent);
+      // Allocate to new image and get new index.
+      $transparent =  (isset($color['alpha']))
+        ? imagecolorallocatealpha($res, $color['red'], $color['green'], $color['blue'], $color['alpha'])
+        : imagecolorallocate($res, $color['red'], $color['green'], $color['blue']);
+
+      $transparent = imagecolorallocate($res,  $transparent['red'], $transparent['green'],  $transparent['blue']);
+      // Flood with our new transparent color.
+      imagefill($res, 0, 0, $transparent);
+      // Tell the new image which color is transparent.
+      imagecolortransparent($res, $transparent);
+    }
+  }
+  elseif ($image->info['extension'] == 'png') {
+    imagealphablending($res, FALSE);
+    $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
+    imagefill($res, 0, 0, $transparency);
+    imagealphablending($res, TRUE);
+    imagesavealpha($res, TRUE);
   }
+  return $res;
 }
 
 /**
Index: includes/file.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/file.inc,v
retrieving revision 1.156
diff -u -r1.156 file.inc
--- includes/file.inc	31 Jan 2009 16:50:56 -0000	1.156
+++ includes/file.inc	13 Feb 2009 00:23:18 -0000
@@ -1145,13 +1145,14 @@
       list($width, $height) = explode('x', $maximum_dimensions);
       if ($info['width'] > $width || $info['height'] > $height) {
         // Try to resize the image to fit the dimensions.
-        if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
+        if (image_get_toolkit() && $image = image_open($file->filepath)) {
+          image_scale($image, $width, $height);
+          image_close($image);
           drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
 
           // Clear the cached filesize and refresh the image information.
           clearstatcache();
-          $info = image_get_info($file->filepath);
-          $file->filesize = $info['file_size'];
+          $file->filesize = $image->info['file_size'];
         }
         else {
           $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
Index: includes/image.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/image.inc,v
retrieving revision 1.28
diff -u -r1.28 image.inc
--- includes/image.inc	30 Dec 2008 16:43:14 -0000	1.28
+++ includes/image.inc	13 Feb 2009 00:23:18 -0000
@@ -65,10 +65,9 @@
   if (!$toolkit) {
     $toolkit = variable_get('image_toolkit', 'gd');
     if (isset($toolkit) &&
-      drupal_function_exists("image_" . $toolkit . "_resize")) {
+      drupal_function_exists('image_' . $toolkit . '_resize')) {
     }
-    elseif (!drupal_function_exists("image_gd_check_settings") ||
-      !image_gd_check_settings()) {
+    elseif (!drupal_function_exists('image_gd_check_settings') || !image_gd_check_settings()) {
       $toolkit = FALSE;
     }
   }
@@ -83,17 +82,19 @@
  *   A string containing the method to invoke.
  * @param $params
  *   An optional array of parameters to pass to the toolkit method.
+ * @param $toolkit
+ *   Optional. The toolkit on which to invoke the desired method.
  * @return
  *   Mixed values (typically Boolean indicating successful operation).
  */
-function image_toolkit_invoke($method, $params = array()) {
-  if ($toolkit = image_get_toolkit()) {
+function image_toolkit_invoke($method, $params = array(), $toolkit = NULL) {
+  if (isset($toolkit) || $toolkit = image_get_toolkit()) {
     $function = 'image_' . $toolkit . '_' . $method;
     if (drupal_function_exists($function)) {
       return call_user_func_array($function, $params);
     }
     else {
-      watchdog('php', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $toolkit, '%function' => $function), WATCHDOG_ERROR);
+      watchdog('image', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $toolkit, '%function' => $function), WATCHDOG_ERROR);
       return FALSE;
     }
   }
@@ -137,100 +138,138 @@
 }
 
 /**
- * Scales an image to the exact width and height given. Achieves the
- * target aspect ratio by cropping the original image equally on both
- * sides, or equally on the top and bottom. This function is, for
- * example, useful to create uniform sized avatars from larger images.
+ * Open an image file and return an image object.
  *
- * The resulting image always has the exact target dimensions.
+ * Any changes to the file are not saved until image_close() is called.
  *
- * @param $source
- *   The file path of the source image.
- * @param $destination
- *   The file path of the destination image.
- * @param $width
- *   The target width, in pixels.
- * @param $height
- *   The target height, in pixels.
+ * @param $file
+ *   Path to an image file.
+ * @param $toolkit
+ *   An optional, image toolkit name to override the default.
  * @return
- *   TRUE or FALSE, based on success.
+ *   An image object or FALSE if there was a problem opening the file.
+ * @see image_close()
  */
-function image_scale_and_crop($source, $destination, $width, $height) {
-  $info = image_get_info($source);
-
-  $scale = max($width / $info['width'], $height / $info['height']);
-  $x = round(($info['width'] * $scale - $width) / 2);
-  $y = round(($info['height'] * $scale - $height) / 2);
+function image_open($file, $toolkit = FALSE) {
+  if (!$toolkit) {
+    $toolkit = image_get_toolkit();
+  }
+  if ($toolkit) {
+    $image = new stdClass();
+    $image->source = $file;
+    $image->info = image_get_info($file);
+    $image->toolkit = $toolkit;
+    if ($image = image_toolkit_invoke('open', array($image), $toolkit)) {
+      return $image;
+    }
+  }
+  return FALSE;
+}
 
-  if (image_toolkit_invoke('resize', array($source, $destination, $info['width'] * $scale, $info['height'] * $scale))) {
-    return image_toolkit_invoke('crop', array($destination, $destination, $x, $y, $width, $height));
+/**
+ * Close the image and save the changes to a file.
+ *
+ * @param $image
+ *   An image object returned by image_load().
+ * @param $destination
+ *   Destination path where the image should be saved. If it is empty the
+ *   original image file will be overwritten.
+ * @see image_load()
+ */
+function image_close($image, $destination = NULL) {
+  if (empty($destination)) {
+    $destination = $image->source;
+  }
+  if ($return = image_toolkit_invoke('close', array($image, $destination), $image->toolkit)) {
+    if (@chmod($destination, 0664)) {
+      return $return;
+    }
+    watchdog('image', 'Could not set permissions on destination file: %file', array('%file' => $destination));
   }
   return FALSE;
 }
 
 /**
- * Scales an image to the given width and height while maintaining aspect
- * ratio.
+ * Scales an image to the given width and height while maintaining aspect ratio.
  *
  * The resulting image can be smaller for one or both target dimensions.
  *
- * @param $source
- *   The file path of the source image.
- * @param $destination
- *   The file path of the destination image.
+ * @param $image
+ *   An image object returned by image_open().
  * @param $width
- *   The target width, in pixels.
+ *   The target width in pixels.
  * @param $height
- *   The target height, in pixels.
+ *   The target height in pixels.
+ * @param $upscale
+ *   Allow upscaling.
  * @return
- *   TRUE or FALSE, based on success.
+ *   True or false, based on success.
+ * @see image_open()
+ * @see image_scale_and_crop()
  */
-function image_scale($source, $destination, $width, $height) {
-  $info = image_get_info($source);
+function image_scale(&$image, $width = NULL, $height = NULL, $upscale = FALSE) {
+  if (!isset($upscale)) {
+    // Set impossibly large values if the width and height aren't set.
+    $width = !empty($width) ? $width : 9999999;
+    $width = !empty($height) ? $height : 9999999;
+  }
+
+  // Set width/height according to aspect ratio if either is empty.
+  $aspect = $image->info['height'] / $image->info['width'];
+  if (empty($height)) {
+    $height = $width / $aspect;
+  }
+  if (empty($width)) {
+    $width = $height * $aspect;
+  }
 
   // Don't scale up.
-  if ($width >= $info['width'] && $height >= $info['height']) {
-    return FALSE;
+  if (!$upscale && round($width) >= $image->info['width'] && round($height) >= $image->info['height']) {
+    return TRUE;
   }
 
-  $aspect = $info['height'] / $info['width'];
+  $aspect = $image->info['height'] / $image->info['width'];
   if ($aspect < $height / $width) {
-    $width = (int)min($width, $info['width']);
-    $height = (int)round($width * $aspect);
+    $height = $width * $aspect;
   }
   else {
-    $height = (int)min($height, $info['height']);
-    $width = (int)round($height / $aspect);
+    $width = $height / $aspect;
   }
 
-  return image_toolkit_invoke('resize', array($source, $destination, $width, $height));
+  $width = (int) round($width);
+  $height = (int) round($height);
+
+  return image_toolkit_invoke('resize', array($image, $width, $height), $image->toolkit);
 }
 
+
 /**
  * Resize an image to the given dimensions (ignoring aspect ratio).
  *
- * @param $source
- *   The file path of the source image.
- * @param $destination
- *   The file path of the destination image.
+ * @param $image
+ *   An image object returned by image_open().
  * @param $width
- *   The target width, in pixels.
+ *   The target width in pixels.
  * @param $height
- *   The target height, in pixels.
-  * @return
- *   TRUE or FALSE, based on success.
+ *   The target height in pixels.
+ * @param $toolkit
+ *   An optional override of the default image toolkit.
+ * @return
+ *   True or false, based on success.
+ * @see image_open()
  */
-function image_resize($source, $destination, $width, $height) {
-  return image_toolkit_invoke('resize', array($source, $destination, $width, $height));
+function image_resize(&$image, $width, $height) {
+  $width = (int) round($width);
+  $height = (int) round($height);
+
+  return image_toolkit_invoke('resize', array($image, $width, $height), $image->toolkit);
 }
 
 /**
  * Rotate an image by the given number of degrees.
  *
- * @param $source
- *   The file path of the source image.
- * @param $destination
- *   The file path of the destination image.
+ * @param $image
+ *   An image object returned by image_open().
  * @param $degrees
  *   The number of (clockwise) degrees to rotate the image.
  * @param $background
@@ -239,31 +278,86 @@
  *   0xff00ff for magenta, and 0xffffff for white.
  * @return
  *   TRUE or FALSE, based on success.
+ * @see image_open()
  */
-function image_rotate($source, $destination, $degrees, $background = 0x000000) {
-  return image_toolkit_invoke('rotate', array($source, $destination, $degrees, $background));
+function image_rotate(&$image, $degrees, $background = 0x000000) {
+  return image_toolkit_invoke('resize', array($image, $degrees, $background), $image->toolkit);
 }
 
 /**
  * Crop an image to the rectangle specified by the given rectangle.
  *
- * @param $source
- *   The file path of the source image.
- * @param $destination
- *   The file path of the destination image.
+ * @param $image
+ *   An image object returned by image_open().
  * @param $x
- *   The top left co-ordinate, in pixels, of the crop area (x axis value).
+ *   The top left co-ordinate of the crop area (x axis value).
  * @param $y
- *   The top left co-ordinate, in pixels, of the crop area (y axis value).
+ *   The top left co-ordinate of the crop area (y axis value).
+ * @param $width
+ *   The target width in pixels.
+ * @param $height
+ *   The target height in pixels.
+ * @return
+ *   True or false, based on success.
+ * @see image_open()
+ * @see image_scale_and_crop()
+ */
+function image_crop(&$image, $x, $y, $width, $height) {
+  $aspect = $image->info['height'] / $image->info['width'];
+  if (empty($height)) $height = $width / $aspect;
+  if (empty($width)) $width = $height * $aspect;
+
+  $width = (int) round($width);
+  $height = (int) round($height);
+
+  return image_toolkit_invoke('crop', array($image, $x, $y, $width, $height), $image->toolkit);
+}
+
+/**
+ * Scales an image to the exact width and height given.
+ * 
+ * This function achieves the target aspect ratio by cropping the original image
+ * equally on both sides, or equally on the top and bottom. This function is
+ * useful to create uniform sized avatars from larger images.
+ *
+ * The resulting image always has the exact target dimensions.
+ *
+ * @param $image
+ *   An image object returned by image_load().
  * @param $width
- *   The target width, in pixels.
+ *   The target width in pixels.
  * @param $height
- *   The target height, in pixels.
+ *   The target height in pixels.
+ * @return
+ *   True or false, based on success.
+ * @see image_load()
+ */
+function image_scale_and_crop(&$image, $width, $height) {
+  $aspect = $image->info['height'] / $image->info['width'];
+  if (empty($height)) $height = $width / $aspect;
+  if (empty($width)) $width = $height * $aspect;
+
+  $scale = max($width / $image->info['width'], $height / $image->info['height']);
+  $x = (int) round(($image->info['width'] * $scale - $width) / 2);
+  $y = (int) round(($image->info['height'] * $scale - $height) / 2);
+
+  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
+    return image_crop($image, $x, $y, $width, $height);
+  }
+  return false;
+}
+
+/**
+ * Convert an image to grayscale.
+ *
+ * @param $image
+ *   An image object returned by image_open().
  * @return
  *   TRUE or FALSE, based on success.
+ * @see image_load()
  */
-function image_crop($source, $destination, $x, $y, $width, $height) {
-  return image_toolkit_invoke('crop', array($source, $destination, $x, $y, $width, $height));
+function image_desaturate(&$image) {
+  return image_toolkit_invoke('desaturate', array($image), $image->toolkit);
 }
 
 /**
