? .cache
? .project
? .settings
? drupal_image_handling_1.patch
? includes/junk
? modules/system/image.actions.inc
? modules/system/system.admin_image.inc
? sites/all/modules/cvs_deploy
? sites/all/modules/devel
? sites/all/modules/drush
? sites/all/modules/imageapi
? sites/default/files
? sites/default/settings.php
Index: includes/common.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/common.inc,v
retrieving revision 1.865
diff -u -p -r1.865 common.inc
--- includes/common.inc	9 Feb 2009 03:29:53 -0000	1.865
+++ includes/common.inc	12 Feb 2009 19:18:36 -0000
@@ -3538,6 +3538,9 @@ function drupal_common_theme() {
     'image' => array(
       'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
     ),
+    'image_preset' => array(
+      'arguments' => array('preset' => NULL, 'path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
+    ),
     'breadcrumb' => array(
       'arguments' => array('breadcrumb' => NULL),
     ),
Index: includes/file.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/file.inc,v
retrieving revision 1.156
diff -u -p -r1.156 file.inc
--- includes/file.inc	31 Jan 2009 16:50:56 -0000	1.156
+++ includes/file.inc	12 Feb 2009 19:18:36 -0000
@@ -801,6 +801,37 @@ function file_unmanaged_delete($path) {
   return FALSE;
 }
 
+
+/**
+ * Recursively delete all files and folders in the specified filepath.
+ *
+ * After the containing directory's files are deleted, the containing folder is
+ * also removed. Note that this only deletes visible files with write
+ * permission.
+ *
+ * @param $path
+ *   A string containing a file path.
+ */
+function file_unmanaged_delete_recursive($path) {
+  if (is_file($path) || is_link($path)) {
+    unlink($path);
+  }
+  elseif (is_dir($path)) {
+    $dir = dir($path);
+    while (($entry = $dir->read()) !== false) {
+      if ($entry == '.' || $entry == '..') {
+        continue;
+      }
+      $entry_path = $path .'/'. $entry;
+      file_unmanaged_delete_recursive($entry_path);
+    }
+    rmdir($path);
+  }
+  else {
+    watchdog('file', 'Unknown file type(%path) stat: %stat ', 
+              array('%path' => $path,  '%stat' => print_r(stat($path),1)), WATCHDOG_ERROR);
+  }
+}
 /**
  * Determine total disk space used by a single user or the whole filesystem.
  *
@@ -1145,13 +1176,14 @@ function file_validate_image_resolution(
       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 -p -r1.28 image.inc
--- includes/image.inc	30 Dec 2008 16:43:14 -0000	1.28
+++ includes/image.inc	12 Feb 2009 19:18:36 -0000
@@ -65,10 +65,9 @@ function image_get_toolkit() {
   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 @@ function image_get_toolkit() {
  *   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 @@ function image_get_info($file) {
 }
 
 /**
- * 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,603 @@ function image_resize($source, $destinat
  *   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_desaturate(&$image) {
+  return image_toolkit_invoke('desaturate', array($image), $image->toolkit);
+}
+
+/**
+ * Get an array of all presets and their settings.
+ *
+ * @param $reset
+ *   If set to TRUE the internal preset cache will be cleared.
+ * @return
+ *   Array of presets array($pid => array('id' => integer, 'name' => string)).
+ */
+function image_presets($reset = FALSE) {
+  static $presets = array();
+
+  // Clear  caches if $reset is true;
+  if ($reset) {
+    $presets = array();
+    cache_clear_all('image_presets', 'cache');
+  }
+
+  // Grab from cache or build the array.
+  if ($cache = cache_get('image_presets', 'cache')) {
+    $presets = $cache->data;
+  }
+  else {
+    $result = db_query('SELECT * FROM {image_presets} ORDER BY name');
+    while ($preset = db_fetch_array($result)) {
+      $presets[$preset['name']] = $preset;
+      $presets[$preset['name']]['actions'] = image_preset_actions($preset, $reset);
+    }
+    cache_set('image_presets', $presets);
+  }
+
+  return $presets;
+}
+
+/**
+ * Get an array of image presets suitable for using as select list options.
+ */
+function image_preset_options($include_empty = TRUE) {
+  $presets = image_presets();
+  $options = array();
+  if ($include_empty && !empty($presets)) {
+    $options[''] = t('<none>');
+  }
+  $options = array_merge($options, drupal_map_assoc(array_keys($presets)));
+  if (empty($options)) {
+    $options[''] = t('No defined presets');
+  }
+  return $options;
+}
+
+/**
+ * Load a preset by preset name or ID. May be used as a loader for menu items.
+ *
+ * @param $name
+ *   The name of the preset.
+ * @param $pid
+ *   Optional. The numeric id of a preset if the name is not known.
+ *
+ * @return
+ *   An image preset with the format of
+ *   array('name' => string, 'id' => integer).
+ *   If the preset name or ID is not valid, an empty array is returned.
+ */
+function image_preset_load($name = NULL, $pid = NULL, $reset = FALSE) {
+  $presets = image_presets($reset);
+
+  // If retrieving by name.
+  if (isset($name) && isset($presets[$name])) {
+    return $presets[$name];
+  }
+
+  // If retrieving by PID.
+  if (isset($pid)) {
+    foreach ($presets as $name => $preset) {
+      if ($preset['ipid'] == $pid) {
+        return $preset;
+      }
+    }
+  }
+
+  // Otherwise the preset was not found.
+  return array();
+}
+
+/**
+ * Save an image preset.
+ *
+ * @param preset
+ *   An image preset array.
+ * @return
+ *   A preset array.  In the case of a new preset, 'ipid' will be populated.
+ */
+function image_preset_save($preset) {
+  if (isset($preset['ipid']) && is_numeric($preset['ipid'])) {
+    drupal_write_record('image_presets', $preset, 'ipid');
+  }
+  else {
+    drupal_write_record('image_presets', $preset);
+  }
+
+  // Reset presets cache.
+  image_preset_flush($preset);
+  image_presets(TRUE);
+  menu_rebuild();
+
+  return $preset;
+}
+
+/**
+ * Delete an image preset.
+ *
+ * @param preset
+ *   An image preset array.
+ */
+function image_preset_delete($preset) {
+  image_preset_flush($preset);
+  db_query('DELETE FROM {image_actions} where ipid = %d', $preset['ipid']);
+  db_query('DELETE FROM {image_presets} where ipid = %d', $preset['ipid']);
+  image_presets(TRUE);
+  menu_rebuild();
+  return TRUE;
+}
+
+/**
+ * Load all the actions for an image preset.
+ *
+ * @param $preset
+ *   An image preset array.
+ * @param $reset
+ *   If set to TRUE the internal cache image actions will be reset.
+ */
+function image_preset_actions($preset, $reset = FALSE) {
+  static $actions;
+
+  if ($reset || !isset($actions)) {
+    $actions = array();
+    $definitions = image_action_definitions($reset);
+    $result = db_query('SELECT * FROM {image_actions} where ipid = %d order by weight', $preset['ipid']);
+    while ($action = db_fetch_array($result)) {
+      $action['data'] = unserialize($action['data']);
+      $action = array_merge($definitions[$action['action']], $action);
+      $actions[$preset['ipid']][] = $action;
+    }
+  }
+
+  return isset($actions[$preset['ipid']]) ? $actions[$preset['ipid']] : array();
+}
+
+/**
+ * Flush cached media for a preset.
+ *
+ * @param $preset
+ *   An image preset.
+ */
+function image_preset_flush($preset) {
+  $preset_directory = realpath(file_directory_path() .'/presets/'. $preset['name']);
+  if (is_dir($preset_directory)) {
+    file_unmanaged_delete_recursive($preset_directory);
+  }
+}
+
+/**
+ * Return a complete URL to an image when using a preset.
+ *
+ * @param $preset_name
+ *   The name of the preset to be used with this image.
+ * @param $path
+ *   The path to the image.
+ * @return
+ *   The complete absolute URL to a preset image.
+ */
+function image_preset_url($preset_name, $path) {
+  $path = _image_strip_file_directory($path);
+  return file_create_url(file_create_path() .'/presets/'. $preset_name .'/'. $path);
+}
+
+/**
+ * Return a relative path to an image when using a preset.
+ *
+ * @param $preset_name
+ *   The name of the preset to be used with this image.
+ * @param $path
+ *   The path to the image.
+ * @param $file_system
+ *   Optional. By default this will return the file system path, which may be
+ *   relative to the Drupal root or an absolute path on the server. If set to
+ *   FALSE, this will return the Drupal path instead, suitable for requesting
+ *   the image.
+ * @param
+ *   The path to an image preset image. If $file_system is TRUE the path may
+ *   be used in an is_file() request. If $file_system is FALSE the path may
+ *   be used in theme('image_preset') or url() requests since it contains a
+ *   Drupal path.
+ */
+function image_preset_path($preset_name, $path, $file_system = TRUE) {
+  $path = _image_strip_file_directory($path);
+  if ($file_system || variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC) {
+    return file_directory_path() . '/presets/' . $preset_name . '/' . $path;
+  }
+  else {
+    return 'system/files/presets/' . $preset_name . '/' . $path;
+  }
+}
+
+/**
+ * Given an image preset and path, generate an image derivative.
+ *
+ * @param $preset_name
+ *   The name of the preset to be used with this image.
+ * @param $path
+ *   The path to the image.
+ * @return
+ *   TRUE if the image is able to be generated successfully or FALSE if unable
+ *   to create the image. This function may return NULL when the image
+ *   generation is in progress but not complete.
+ */
+function image_preset_generate($preset_name, $path) {
+  $default_method = 'system_image_preset_request';
+  $path = _image_strip_file_directory($path);
+  $method = variable_get('image_preset_generation_method', $default_method);
+  $preset = image_preset_load($preset_name);
+  if (drupal_function_exists($method)) {
+    return $method($preset, $path);
+  }
+  else {
+    return $default_method($preset, $path);
+  }
+}
+
+/**
+ * Create a new image based on an image preset.
+ *
+ * @param $preset
+ *   An image preset array.
+ * @param $source
+ *   Path of the source file.
+ * @param $destination
+ *   Path of the destination file.
+ * @return
+ *   TRUE if an image derivative is generated, FALSE if no image
+ *   derivative is generated. NULL if the derivative is being generated.
+ */
+function image_preset_create_derivative($preset, $source, $destination) {
+  // Get the folder for the final location of this preset.
+  $directory = dirname($destination);
+
+  // Build the destination folder tree if it doesn't already exists.
+  if (!file_check_directory($directory, FILE_CREATE_DIRECTORY) && !mkdir($directory, 0775, TRUE)) {
+    watchdog('image', 'Failed to create preset directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
+    return FALSE;
+  }
+
+  if (!$image = image_open($source)) {
+    return FALSE;
+  }
+
+  foreach ($preset['actions'] as $action) {
+    if (!empty($action['data'])) {
+      // Find new width and height of the image if available. This helps
+      // generate appropriate offsets when using keyword values like "center".
+      if (isset($action['data']['width'])) {
+        $width = image_filter_value('width', $action['data']['width'], $image->info['width'], $image->info['height']);
+      }
+      if (isset($action['data']['height'])) {
+        $height = image_filter_value('height', $action['data']['height'], $image->info['width'], $image->info['height']);
+      }
+      // Run image filter on each value.
+      foreach ($action['data'] as $key => $value) {
+        $action['data'][$key] = image_filter_value($key, $value, $image->info['width'], $image->info['height'], $width, $height);
+      }
+    }
+    image_action_apply($image, $action);
+  }
+
+  if (!image_close($image, $destination)) {
+    if (file_exists($destination)) {
+      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
+    }
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+/**
+ * Clear cached versions of a specific file in all presets.
+ *
+ * @param $path
+ *   The Drupal file path to the original image.
+ */
+function image_path_flush($path) {
+  $path = _image_strip_file_directory($path);
+  foreach (image_presets() as $preset) {
+    if ($path = file_create_path('presets/'. $preset['name'] .'/'. $path)) {
+      file_unmanaged_delete($path);
+    }
+  }
+}
+
+/**
+ * Load all image actions from the database.
+ *
+ * @param $reset
+ *   If TRUE, the internal list of actions will be regenerated.
+ */
+function image_actions($reset = FALSE) {
+  static $actions;
+
+  if (!isset($actions) || $reset) {
+    $actions = array();
+
+    // Add database image actions.
+    $result = db_query('SELECT * FROM {image_actions}', NULL, array('fetch' => PDO::FETCH_ASSOC));
+    foreach ($result as $action) {
+      $action['data'] = unserialize($action['data']);
+      $definition = image_action_definition_load($action['action'], $reset);
+      // Do not load actions whose definition cannot be found.
+      if ($definition) {
+        $action = array_merge($definition, $action);
+        $actions[$action['iaid']] = $action;
+      }
+    }
+  }
+
+  return $actions;
+}
+
+/**
+ * Pull in actions exposed by other modules using hook_image_actions().
+ *
+ * @param $reset
+ *   If TRUE, regenerate the internal cache of action definitions.
+ * @return
+ *   An array of actions to be used when transforming images.
+ */
+function image_action_definitions($toolkit = NULL, $reset = FALSE) {
+  static $actions;
+
+  if (!isset($toolkit)) {
+    $toolkit = image_get_toolkit();
+  }
+
+  if (!isset($actions) || $reset) {
+    if (!$reset && ($cache = cache_get('image_actions')) && !empty($cache->data)) {
+      $actions = $cache->data;
+    }
+    else {
+      $actions = array();
+      foreach (module_implements('image_actions') as $module) {
+        foreach (module_invoke($module, 'image_actions') as $key => $action) {
+          // Ensure the current toolkit supports the 
+          $action['module'] = $module;
+          $action['action'] = $key;
+          $action['data'] = isset($action['data']) ? $action['data'] : array();
+          $actions[$key] = $action;
+        };
+      }
+      uasort($actions, '_image_actions_definitions_sort');
+      cache_set('image_actions', $actions);
+    }
+  }
+
+  return $actions;
+}
+
+/**
+ * Load the definition for an action.
+ *
+ * The action definition is a set of default values that applies to an action
+ * regardless of user settings. This definition consists of an array containing
+ * at least the following values:
+ *  - action: The unique name for the action being performed. Usually prefixed
+ *    with the name of the module providing the action.
+ *  - module: The module providing the action.
+ *  - description: A description of the action.
+ *
+ * @param $action
+ *   The name of the action definition to load.
+ * @param $reset
+ *   If TRUE, regenerate the internal cache of action definitions.
+ */
+function image_action_definition_load($action, $reset = FALSE) {
+  static $definition_cache;
+
+  if (!isset($definition_cache[$action]) || $reset) {
+    $definitions = image_action_definitions($reset);
+    $definition = (isset($definitions[$action])) ? $definitions[$action] : array();
+    $definition_cache[$action] = $definition;
+  }
+
+  return isset($definition_cache[$action]) ? $definition_cache[$action] : FALSE;
+}
+
+/**
+ * Load a single image action.
+ *
+ * @param $iaid
+ *   The image action ID.
+ */
+function image_action_load($iaid) {
+  $actions = image_actions();
+  return isset($actions[$iaid]) ? $actions[$iaid] : FALSE;
+}
+
+/**
+ * Save an image action.
+ *
+ * @param $action
+ *   An image action array.
+ */
+function image_action_save($action) {
+  if (!empty($action['iaid'])) {
+    drupal_write_record('image_actions', $action, 'iaid');
+  }
+  else {
+    drupal_write_record('image_actions', $action);
+  }
+  $preset = image_preset_load(NULL, $action['ipid']);
+  image_preset_flush($preset);
+  image_presets(TRUE);
+  return $action; 
+}
+
+/**
+ * Delete an image action.
+ *
+ * @param $action
+ *   An image action array.
+ */
+function image_action_delete($action) {
+  db_query('DELETE FROM {image_actions} WHERE iaid = %d', $action['iaid']);
+  $preset = image_preset_load(NULL, $action['ipid']);
+  image_preset_flush($preset);
+  image_presets(TRUE);
+}
+
+/**
+ * Given an image object and action, perform the action on the file.
+ */
+function image_action_apply(&$image, $action) {
+  if (drupal_function_exists($action['function'])) {
+    return call_user_func($action['function'], $image, $action['data']);
+  }
+  return FALSE;
+}
+
+/**
+ * Filter key word values such as 'top', 'right', 'center', and percentages.
+ *
+ * All returned values are in pixels relative to the passed in height and width.
+ */
+function image_filter_value($key, $value, $current_width, $current_height, $new_width = null, $new_height = null) {
+  switch ($key) {
+    case 'width':
+      $value = _image_filter_percent($value, $current_width);
+      break;
+    case 'height':
+      $value = _image_filter_percent($value, $current_height);
+      break;
+    case 'xoffset':
+      $value = _image_filter_keyword($value, $current_width, $new_width);
+      break;
+    case 'yoffset':
+      $value = _image_filter_keyword($value, $current_height, $new_height);
+      break;
+  }
+  return $value;
+}
+
+/**
+ * Accept a percentage and return it in pixels.
+ */
+function _image_filter_percent($value, $current_pixels) {
+  if (strpos($value, '%') !== false) {
+    $value = str_replace('%', '', $value) * 0.01 * $current_pixels;
+  }
+  return $value;
+}
+
+/**
+ * Accept a keyword (center, top, left, etc) and return it as an offset in pixels.
+ */
+function _image_filter_keyword($value, $current_pixels, $new_pixels) {
+  switch ($value) {
+    case 'top':
+    case 'left':
+      $value = 0;
+      break;
+    case 'bottom':
+    case 'right':
+      $value = $current_pixels - $new_pixels;
+      break;
+    case 'center':
+      $value = $current_pixels/2 - $new_pixels/2;
+      break;
+  }
+  return $value;
+}
+
+/**
+ * Remove a possible leading file directory path from the given path.
+ */
+function _image_strip_file_directory($path) {
+  $dirpath = file_directory_path();
+  $dirlen = strlen($dirpath);
+  if (substr($path, 0, $dirlen + 1) == $dirpath .'/') {
+    $path = substr($path, $dirlen + 1);
+  }
+  return $path;
+}
+
+/**
+ * Internal function for sorting image action definitions through uasort().
  */
-function image_crop($source, $destination, $x, $y, $width, $height) {
-  return image_toolkit_invoke('crop', array($source, $destination, $x, $y, $width, $height));
+function _image_actions_definitions_sort($a, $b) {
+  return strcasecmp($a['name'], $b['name']);
 }
 
 /**
Index: includes/theme.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/theme.inc,v
retrieving revision 1.469
diff -u -p -r1.469 theme.inc
--- includes/theme.inc	5 Feb 2009 03:42:56 -0000	1.469
+++ includes/theme.inc	12 Feb 2009 19:18:37 -0000
@@ -1211,11 +1211,44 @@ function theme_links($links, $attributes
  *   A string containing the image tag.
  */
 function theme_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
-  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
-    $attributes = drupal_attributes($attributes);
-    $url = (url($path) == $path) ? $path : (base_path() . $path);
-    return '<img src="' . check_url($url) . '" alt="' . check_plain($alt) . '" title="' . check_plain($title) . '" ' . (isset($image_attributes) ? $image_attributes : '') . $attributes . ' />';
+  if ($getsize && (is_file($path))) {
+    list($width, $height, $type, $image_attributes) = @getimagesize($path);
   }
+
+  $attributes = drupal_attributes($attributes);
+  $url = (url($path) == $path) ? $path : (base_path() . $path);
+  return '<img src="' . check_url($url) . '" alt="' . check_plain($alt) . '" title="' . check_plain($title) . '" ' . (isset($image_attributes) ? $image_attributes : '') . $attributes . ' />';
+}
+
+/**
+ * Return a themed image using a specific image preset.
+ *
+ * @param $preset
+ *   The name of the preset to be used to alter the original image.
+ * @param $path
+ *   The path of the image file relative to the Drupal files directory.
+ *   This function does not work with images outside the files directory nor
+ *   with remotely hosted images.
+ * @param $alt
+ *   The alternative text for text-based browsers.
+ * @param $title
+ *   The title text is displayed when the image is hovered in some popular browsers.
+ * @param $attributes
+ *   Associative array of attributes to be placed in the img tag.
+ * @param $getsize
+ *   If set to TRUE, the image's dimension are fetched and added as width/height attributes.
+ * @return
+ *   A string containing the image tag.
+ */
+function theme_image_preset($preset, $path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
+  $real_path = image_preset_path($preset, $path);
+  $url_path = image_preset_path($preset, $path, FALSE);
+
+  if (!file_exists($real_path)) {
+    image_preset_generate($preset, $path);
+  }
+
+  return theme('image', $url_path, $alt, $title, $attributes, $getsize);
 }
 
 /**
Index: modules/system/image.gd.inc
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/image.gd.inc,v
retrieving revision 1.3
diff -u -p -r1.3 image.gd.inc
--- modules/system/image.gd.inc	30 Dec 2008 16:43:19 -0000	1.3
+++ modules/system/image.gd.inc	12 Feb 2009 19:18:37 -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'),
+  );
 }
 
 /**
@@ -77,117 +80,66 @@ function image_gd_check_settings() {
 /**
  * Scale an image to the specified size using GD.
  */
-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;
+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.
  */
-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);
-
-  return $result;
+  // 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;
 }
 
 /**
  * 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.
  * @return
- *   An image resource, or FALSE on error.
+ *   The image object with an image resource added.
  */
-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;
 }
 
 /**
@@ -202,18 +154,61 @@ function image_gd_open($file, $extension
  * @return
  *   Boolean indicating success.
  */
-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);
+  }
+}
+
+/**
+ * Convert an image resource to grayscale.
+ */
+function image_gd_desaturate(&$image) {
+  return imagefilter($image->res, IMG_FILTER_GRAYSCALE);
+}
+
+/**
+ * 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: modules/system/system.admin.inc
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.admin.inc,v
retrieving revision 1.125
diff -u -p -r1.125 system.admin.inc
--- modules/system/system.admin.inc	11 Feb 2009 05:33:18 -0000	1.125
+++ modules/system/system.admin.inc	12 Feb 2009 19:18:37 -0000
@@ -1455,31 +1455,6 @@ function system_file_system_settings() {
 }
 
 /**
- * Form builder; Configure site image toolkit usage.
- *
- * @ingroup forms
- * @see system_settings_form()
- */
-function system_image_toolkit_settings() {
-  $toolkits_available = image_get_available_toolkits();
-  if (count($toolkits_available) > 1) {
-    $form['image_toolkit'] = array(
-      '#type' => 'radios',
-      '#title' => t('Select an image processing toolkit'),
-      '#default_value' => image_get_toolkit(),
-      '#options' => $toolkits_available
-    );
-  }
-  elseif (count($toolkits_available) == 1) {
-    variable_set('image_toolkit', key($toolkits_available));
-  }
-
-  $form['image_toolkit_settings'] = image_toolkit_invoke('settings');
-
-  return system_settings_form($form, TRUE);
-}
-
-/**
  * Form builder; Configure how the site handles RSS feeds.
  *
  * @ingroup forms
Index: modules/system/system.info
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.info,v
retrieving revision 1.11
diff -u -p -r1.11 system.info
--- modules/system/system.info	12 Oct 2008 01:23:06 -0000	1.11
+++ modules/system/system.info	12 Feb 2009 19:18:37 -0000
@@ -6,6 +6,8 @@ version = VERSION
 core = 7.x
 files[] = system.module
 files[] = system.admin.inc
+files[] = system.admin_image.inc
 files[] = image.gd.inc
+files[] = image.actions.inc
 files[] = system.install
 required = TRUE
Index: modules/system/system.install
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.install,v
retrieving revision 1.306
diff -u -p -r1.306 system.install
--- modules/system/system.install	3 Feb 2009 12:30:14 -0000	1.306
+++ modules/system/system.install	12 Feb 2009 19:18:37 -0000
@@ -726,6 +726,63 @@ function system_schema() {
       'nid' => array('nid'),
     ),
   );
+
+  $schema['image_presets'] = array(
+    'fields' => array(
+      'ipid' => array(
+        'description' => t('The primary identifier for an image preset.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE),
+      'name' => array(
+        'description' => t('The primary identifier for a node.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE),
+    ),
+    'primary key' => array('ipid'),
+    'indexes' => array(
+      'name' => array('name'),
+    ),
+  );
+
+  $schema['image_actions'] = array(
+    'fields' => array(
+      'iaid' => array(
+        'description' => t('The primary identifier for an image action.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE),
+      'ipid' => array(
+        'description' => t('The primary identifier for an image preset.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0),
+      'weight' => array(
+        'description' => t('The weight of the action in the preset.'),
+        'type' => 'int',
+        'unsigned' => FALSE,
+        'not null' => TRUE,
+        'default' => 0),
+      'action' => array(
+        'description' => t('The unique ID of the action to be executed.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE),
+      'data' => array(
+        'description' => t('The configuration data for the action.'),
+        'type' => 'text',
+        'not null' => TRUE,
+        'size' => 'big',
+        'serialize' => TRUE),
+    ),
+    'primary key' => array('iaid'),
+    'indexes' => array(
+      'ipid' => array('ipid'),
+    ),
+  );
+
   $schema['menu_router'] = array(
     'description' => 'Maps paths to various callbacks (access, page and title)',
     'fields' => array(
@@ -3213,6 +3270,74 @@ function system_update_7018() {
 }
 
 /**
+ * Add tables for image presets and actions.
+ */
+function system_update_7019() {
+  $ret = array();
+  $schema = array();
+
+  $schema['image_presets'] = array(
+    'fields' => array(
+      'ipid' => array(
+        'description' => t('The primary identifier for an image preset.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE),
+      'name' => array(
+        'description' => t('The primary identifier for a node.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE),
+    ),
+    'primary key' => array('ipid'),
+    'indexes' => array(
+      'name' => array('name'),
+    ),
+  );
+
+  $schema['image_actions'] = array(
+    'fields' => array(
+      'iaid' => array(
+        'description' => t('The primary identifier for an image action.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE),
+      'ipid' => array(
+        'description' => t('The primary identifier for an image preset.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0),
+      'weight' => array(
+        'description' => t('The weight of the action in the preset.'),
+        'type' => 'int',
+        'unsigned' => FALSE,
+        'not null' => TRUE,
+        'default' => 0),
+      'action' => array(
+        'description' => t('The unique ID of the action to be executed.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE),
+      'data' => array(
+        'description' => t('The configuration data for the action.'),
+        'type' => 'text',
+        'not null' => TRUE,
+        'size' => 'big',
+        'serialize' => TRUE),
+    ),
+    'primary key' => array('iaid'),
+    'indexes' => array(
+      'ipid' => array('ipid'),
+    ),
+  );
+
+  db_create_table($ret, 'image_presets', $schema['image_presets']);
+  db_create_table($ret, 'image_actions', $schema['image_actions']);
+  return $ret;
+}
+
+/**
  * @} End of "defgroup updates-6.x-to-7.x"
  * The next series of updates should start at 8000.
  */
Index: modules/system/system.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.module,v
retrieving revision 1.667
diff -u -p -r1.667 system.module
--- modules/system/system.module	11 Feb 2009 05:33:18 -0000	1.667
+++ modules/system/system.module	12 Feb 2009 19:18:37 -0000
@@ -155,6 +155,38 @@ function system_theme() {
       'arguments' => array('content' => NULL),
       'file' => 'system.admin.inc',
     ),
+    'admin_image_presets' => array(
+      'arguments' => array('presets' => NULL),
+      'file' => 'system.admin.inc',
+    ),
+    'admin_image_preset_actions' => array(
+      'arguments' => array('form' => NULL),
+      'file' => 'system.admin.inc',
+    ),
+    'admin_image_preset_actions_add' => array(
+      'arguments' => array('form' => NULL),
+      'file' => 'system.admin.inc',
+    ),
+    'system_image_resize_summary' => array(
+      'arguments' => array('data' => NULL),
+      'file' => 'image.actions.inc',
+    ),
+    'system_image_scale_summary' => array(
+      'arguments' => array('data' => NULL),
+      'file' => 'image.actions.inc',
+    ),
+    'system_image_crop_summary' => array(
+      'arguments' => array('data' => NULL),
+      'file' => 'image.actions.inc',
+    ),
+    'system_image_desaturate_summary' => array(
+      'arguments' => array('data' => NULL),
+      'file' => 'image.actions.inc',
+    ),
+    'system_image_rotate_summary' => array(
+      'arguments' => array('data' => NULL),
+      'file' => 'image.actions.inc',
+    ),
     'system_admin_by_module' => array(
       'arguments' => array('menu_items' => NULL),
       'file' => 'system.admin.inc',
@@ -189,6 +221,10 @@ function system_perm() {
       'title' => t('Administer files'),
       'description' => t('Manage user-uploaded files.'),
     ),
+    'administer image presets' => array(
+      'title' => t('Administer image presets'),
+      'description' => t('Create and modify presets for generating image modifications such as thumbnails.'),
+    ),
     'access administration pages' => array(
       'title' => t('Access administration pages'),
       'description' => t('View the administration panel and browse the help system.'),
@@ -453,6 +489,12 @@ function system_menu() {
     'access callback' => TRUE,
     'type' => MENU_CALLBACK,
   );
+  $items['system/image'] = array(
+    'title' => 'Generate image preset',
+    'page callback' => 'system_image_preset_generate',
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+  );
   $items['admin'] = array(
     'title' => 'Administer',
     'access arguments' => array('access administration pages'),
@@ -663,12 +705,105 @@ function system_menu() {
     'page arguments' => array('system_file_system_settings'),
     'access arguments' => array('administer site configuration'),
   );
-  $items['admin/settings/image-toolkit'] = array(
+  $items['admin/settings/images'] = array(
+    'title' => 'Image handling',
+    'description' => 'Configure presets for generating image thumbnails and select an image toolkit.',
+    'page callback' => 'system_image_presets',
+    'access arguments' => array('administer site configuration'),
+  );
+  $items['admin/settings/images/presets'] = array(
+    'title' => 'Image presets',
+    'description' => 'Configure presets for generating image thumbnails and other manipulations.',
+    'page callback' => 'system_image_presets',
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => 1,
+  );
+  $items['admin/settings/images/presets/%image_preset'] = array(
+    'title' => 'Edit preset',
+    'title callback' => 'system_image_preset_title',
+    'title arguments' => array('Edit preset !name', 4),
+    'description' => 'Configure an image preset.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_preset_form', 4),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/%image_preset/delete'] = array(
+    'title' => 'Delete preset',
+    'title callback' => 'system_image_preset_title',
+    'title arguments' => array('Delete preset !name', 4),
+    'description' => 'Configure presets for generating image thumbnails and other manipulations.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_preset_delete_form', 4, TRUE),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/%image_preset/flush'] = array(
+    'title' => 'Flush preset',
+    'title callback' => 'system_image_preset_title',
+    'title arguments' => array('Flush preset !name', 4),
+    'description' => 'Flush all the created images for a preset.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_preset_flush_form', 4, TRUE),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/%image_preset/%image_action'] = array(
+    'title' => 'Edit image action',
+    'title callback' => 'system_image_action_title',
+    'title arguments' => array('Edit !name action', 5),
+    'description' => 'Edit an exiting action within a preset.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_action_form', 4, 5),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/%image_preset/%image_action/delete'] = array(
+    'title' => 'Delete image action',
+    'title callback' => 'system_image_action_title',
+    'title arguments' => array('Delete !name action', 5),
+    'description' => 'Delete an exiting action from a preset.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_action_delete_form', 4, 5),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/%image_preset/add/%image_action_definition'] = array(
+    'title' => 'Add image action',
+    'title callback' => 'system_image_action_title',
+    'title arguments' => array('Add !name action', 6),
+    'description' => 'Add a new action to a preset.',
+    'page callback' => 'system_image_admin_form',
+    'page arguments' => array('system_image_action_form', 4, 6),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/settings/images/presets/list'] = array(
+    'title' => 'List',
+    'description' => 'List the current image presets on the site.',
+    'page callback' => 'system_image_presets',
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => 1,
+  );
+  $items['admin/settings/images/presets/add'] = array(
+    'title' => 'Add preset',
+    'description' => 'Add a new image preset.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('system_image_preset_add_form'),
+    'access arguments' => array('administer image presets'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 2,
+  );
+  $items['admin/settings/images/toolkit'] = array(
     'title' => 'Image toolkit',
     'description' => 'Choose which image toolkit to use if you have installed optional toolkits.',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('system_image_toolkit_settings'),
     'access arguments' => array('administer site configuration'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 2,
   );
   $items['admin/content/rss-publishing'] = array(
     'title' => 'RSS publishing',
@@ -1073,6 +1208,49 @@ function system_get_files_database(&$fil
 }
 
 /**
+ * Implementation of hook_file_download().
+ *
+ * Control the access to files underneath the system/files/presets directory.
+ */
+function system_file_download($filepath) {
+  if (strpos($filepath, 'presets/') === 0) {
+    $args = explode('/', $filepath);
+    array_shift($args); // Toss the "presets" item.
+    $preset_name = array_shift($args);
+    $original_path = implode('/', $args);
+
+    // Check that the file exists and is an image.
+    if ($info = image_get_info(file_create_path($filepath))) {
+      // Check the permissions of the original image to grant access to this image.
+      $headers = module_invoke_all('file_download', $original_path);
+      if (!in_array(-1, $headers)) {
+        return array(
+          'Content-Type: ' . $info['mime_type'],
+          'Content-Length: ' . $info['file_size'],
+        );
+      }
+    }
+    return -1;
+  }
+}
+
+/**
+ * Implementation of hook_file_move().
+ */
+function system_file_move($file, $source) {
+  // Delete any image derivatives at the original image path.
+  image_path_flush($file->filepath);
+}
+
+/**
+ * Implementation of hook_file_delete().
+ */
+function system_file_delete($file) {
+  // Delete any image derivatives of this image.
+  image_path_flush($file->filepath);
+}
+
+/**
  * Prepare defaults for themes.
  *
  * @return
Index: modules/user/user.admin.inc
===================================================================
RCS file: /cvs/drupal/drupal/modules/user/user.admin.inc,v
retrieving revision 1.37
diff -u -p -r1.37 user.admin.inc
--- modules/user/user.admin.inc	3 Feb 2009 18:55:32 -0000	1.37
+++ modules/user/user.admin.inc	12 Feb 2009 19:18:37 -0000
@@ -508,10 +508,17 @@ function user_admin_settings() {
     '#maxlength' => 255,
     '#description' => t('URL of picture to display for users with no custom picture selected. Leave blank for none.'),
   );
+  $form['pictures']['settings']['user_picture_preset'] = array(
+    '#type' => 'select',
+    '#title' => t('Upload picture preset'),
+    '#options' => image_preset_options(),
+    '#default_value' => variable_get('user_picture_preset', ''),
+    '#description' => t('Select an image preset to scale user images down without modifying the original image. Image presets may be set up in the <a href="!url">Image handling</a> administration area.', array('!url' => url('admin/settings/images'))),
+  );
   $form['pictures']['settings']['user_picture_dimensions'] = array(
     '#type' => 'textfield',
     '#title' => t('Picture maximum dimensions'),
-    '#default_value' => variable_get('user_picture_dimensions', '85x85'),
+    '#default_value' => variable_get('user_picture_dimensions', '1024x1024'),
     '#size' => 15,
     '#maxlength' => 10,
     '#description' => t('Maximum dimensions for pictures, in pixels.'),
@@ -519,7 +526,7 @@ function user_admin_settings() {
   $form['pictures']['settings']['user_picture_file_size'] = array(
     '#type' => 'textfield',
     '#title' => t('Picture maximum file size'),
-    '#default_value' => variable_get('user_picture_file_size', '30'),
+    '#default_value' => variable_get('user_picture_file_size', '800'),
     '#size' => 15,
     '#maxlength' => 10,
     '#description' => t('Maximum file size for pictures, in kB.'),
Index: modules/user/user.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/user/user.module,v
retrieving revision 1.963
diff -u -p -r1.963 user.module
--- modules/user/user.module	9 Feb 2009 07:36:15 -0000	1.963
+++ modules/user/user.module	12 Feb 2009 19:18:37 -0000
@@ -493,8 +493,8 @@ function user_validate_picture(&$form, &
   // If required, validate the uploaded picture.
   $validators = array(
     'file_validate_is_image' => array(),
-    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
-    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
+    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '1024x1024')),
+    'file_validate_size' => array(variable_get('user_picture_file_size', '800') * 1024),
   );
 
   // Save the file as a temporary file.
@@ -1062,7 +1062,12 @@ function template_preprocess_user_pictur
     }
     if (isset($filepath)) {
       $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
-      $variables['picture'] = theme('image', $filepath, $alt, $alt, '', FALSE);
+      if ($preset = variable_get('user_picture_preset', '')) {
+        $variables['picture'] = theme('image_preset', $preset, $filepath, $alt, $alt, NULL, FALSE);
+      }
+      else {
+        $variables['picture'] = theme('image', $filepath, $alt, $alt, NULL, FALSE);
+      }
       if (!empty($account->uid) && user_access('access user profiles')) {
         $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
         $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes);
@@ -1771,7 +1776,7 @@ function user_edit_form(&$form_state, $u
       '#type' => 'file',
       '#title' => t('Upload picture'),
       '#size' => 48,
-      '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions pixels and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) . ' ' . variable_get('user_picture_guidelines', ''),
+      '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions pixels and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '1024x1024'), '%size' => variable_get('user_picture_file_size', '800'))) . ' ' . variable_get('user_picture_guidelines', ''),
     );
     $form['#validate'][] = 'user_validate_picture';
   }
@@ -1863,6 +1868,9 @@ function _user_cancel($edit, $account, $
       db_delete('users')->condition('uid', $account->uid)->execute();
       db_delete('users_roles')->condition('uid', $account->uid)->execute();
       db_delete('authmap')->condition('uid', $account->uid)->execute();
+      if ($account->picture) {
+        file_delete($account->picture);
+      }
       drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
       watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
       break;
Index: modules/user/user.test
===================================================================
RCS file: /cvs/drupal/drupal/modules/user/user.test,v
retrieving revision 1.28
diff -u -p -r1.28 user.test
--- modules/user/user.test	9 Feb 2009 07:36:15 -0000	1.28
+++ modules/user/user.test	12 Feb 2009 19:18:37 -0000
@@ -547,8 +547,14 @@ class UserPictureTestCase extends Drupal
         // user's profile page.
         $text = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $test_dim));
         $this->assertRaw($text, t('Image was resized.'));
+        if ($preset = variable_get('user_picture_preset', '')) {
+          $url_path = image_preset_path($preset, $pic_path, FALSE);
+        }
+        else {
+          $url_path = $pic_path;
+        }
         $alt = t("@user's picture", array('@user' => $this->user->name));
-        $this->assertRaw(theme('image', $pic_path, $alt, $alt, '', FALSE), t("Image is displayed in user's edit page"));
+        $this->assertRaw(theme('image', $url_path, $alt, $alt, NULL, FALSE), t("Image is displayed in user's edit page"));
 
         // Check if file is located in proper directory.
         $this->assertTrue(is_file($pic_path), t("File is located in proper directory"));
@@ -679,8 +685,14 @@ class UserPictureTestCase extends Drupal
       $pic_path = $this->saveUserPicture($image);
 
       // Check if image is displayed in user's profile page.
+      if ($preset = variable_get('user_picture_preset', '')) {
+        $url_path = image_preset_path($preset, $pic_path, FALSE);
+      }
+      else {
+        $url_path = $pic_path;
+      }
       $this->drupalGet('user');
-      $this->assertRaw($pic_path, t("Image is displayed in user's profile page"));
+      $this->assertRaw($url_path, t("Image is displayed in user's profile page"));
 
       // Check if file is located in proper directory.
       $this->assertTrue(is_file($pic_path), t('File is located in proper directory'));
Index: profiles/default/default.profile
===================================================================
RCS file: /cvs/drupal/drupal/profiles/default/default.profile,v
retrieving revision 1.37
diff -u -p -r1.37 default.profile
--- profiles/default/default.profile	3 Feb 2009 12:30:14 -0000	1.37
+++ profiles/default/default.profile	12 Feb 2009 19:18:37 -0000
@@ -132,6 +132,25 @@ function default_profile_tasks(&$task, $
   // Don't display date and author information for page nodes by default.
   variable_set('node_submitted_page', FALSE);
 
+  // Create an image preset.
+  $preset = array('name' => 'thumbnail_square');
+  $preset = image_preset_save($preset);
+  $action = array(
+    'ipid' => $preset['ipid'],
+    'action' => 'system_image_scale_and_crop',
+    'data' => array('width' => '85', 'height' => '85'),
+  );
+  image_action_save($action);
+
+  // Enable user picture support and set the default to a square thumbnail option.
+  variable_set('user_pictures', '1');
+  variable_set('user_picture_preset', 'thumbnail_square');
+
+  $theme_settings = theme_get_settings();
+  $theme_settings['toggle_node_user_picture'] = '1';
+  $theme_settings['toggle_comment_user_picture'] = '1';
+  variable_set('theme_settings', $theme_settings);
+
   // Create a default vocabulary named "Tags", enabled for the 'article' content type.
   $description = st('Use tags to group articles on similar topics into categories.');
   $help = st('Enter a comma-separated list of words.');
