diff --git a/includes/file.inc b/includes/file.inc index aa3b7f190f527806381bd5f14b2a44714ceab0ed..477f06b5a343f466dab886573ab00b8f768ee33e 100644 --- a/includes/file.inc +++ b/includes/file.inc @@ -1183,13 +1183,11 @@ function file_validate_image_resolution($file, $maximum_dimensions = 0, $minimum 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 = image_load($file->filepath)) { + image_scale($image, $width, $height); + image_save($image); + $file->filesize = $image->info['file_size']; 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']; } else { $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions)); diff --git a/includes/image.inc b/includes/image.inc index a38e234198b07fe3230ade643be46bb3e964169d..6f94810e0015e562b62c825deb752b35d649cfa6 100644 --- a/includes/image.inc +++ b/includes/image.inc @@ -36,20 +36,20 @@ * Return a list of available toolkits. * * @return - * An array of toolkit name => descriptive title. + * An array with the toolkit names as keys and the descriptions as values. */ function image_get_available_toolkits() { // hook_image_toolkits returns an array of toolkit names. $toolkits = module_invoke_all('image_toolkits'); $output = array(); - foreach ($toolkits as $name) { - $function = 'image_' . $name . '_info'; - if (drupal_function_exists($function)) { - $info = $function(); - $output[$info['name']] = $info['title']; + foreach ($toolkits as $name => $info) { + // Only allow modules that aren't marked as unavailable. + if ($info['available']) { + $output[$name] = $info['title']; } } + return $output; } @@ -62,14 +62,13 @@ function image_get_available_toolkits() { function image_get_toolkit() { static $toolkit; - if (!$toolkit) { + if (!isset($toolkit)) { + $toolkits = image_get_available_toolkits(); $toolkit = variable_get('image_toolkit', 'gd'); - if (isset($toolkit) && - drupal_function_exists("image_" . $toolkit . "_resize")) { - } - elseif (!drupal_function_exists("image_gd_check_settings") || - !image_gd_check_settings()) { - $toolkit = FALSE; + if (!isset($toolkits[$toolkit]) || !drupal_function_exists('image_' . $toolkit . '_load')) { + // The selected toolkit isn't available so return the first one found. If + // none are available this will return FALSE. + $toolkit = reset($toolkits); } } @@ -81,25 +80,23 @@ function image_get_toolkit() { * * @param $method * A string containing the method to invoke. + * @param $image + * An image object returned by image_load(). * @param $params * An optional array of parameters to pass to the toolkit method. * @return * Mixed values (typically Boolean indicating successful operation). */ -function image_toolkit_invoke($method, $params = array()) { - if ($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); - return FALSE; - } +function image_toolkit_invoke($method, stdClass $image, array $params = array()) { + $function = 'image_' . $image->toolkit . '_' . $method; + if (drupal_function_exists($function)) { + array_unshift($params, $image); + return call_user_func_array($function, $params); } + watchdog('image', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $image->toolkit, '%function' => $function), WATCHDOG_ERROR); + return FALSE; } - /** * Get details about an image. * @@ -108,8 +105,8 @@ function image_toolkit_invoke($method, $params = array()) { * @return * FALSE, if the file could not be found or is not an image. Otherwise, a * keyed array containing information about the image: - * 'width' - Width in pixels. - * 'height' - Height in pixels. + * 'width' - Width, in pixels. + * 'height' - Height, in pixels. * 'extension' - Commonly used file extension for the image. * 'mime_type' - MIME type ('image/jpeg', 'image/gif', 'image/png'). * 'file_size' - File size in bytes. @@ -137,133 +134,225 @@ 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. + * 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 $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_load(). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. * @return * TRUE or FALSE, based on success. + * + * @see image_load() + * @see image_resize() + * @see image_crop() */ -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_scale_and_crop(stdClass $image, $width, $height) { + $scale = max($width / $image->info['width'], $height / $image->info['height']); + $x = ($image->info['width'] * $scale - $width) / 2; + $y = ($image->info['height'] * $scale - $height) / 2; - 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)); + if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) { + return image_crop($image, $x, $y, $width, $height); } 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_load(). * @param $width - * The target width, in pixels. + * The target width, in pixels. This value is omitted then the scaling will + * based only on the height value. * @param $height - * The target height, in pixels. + * The target height, in pixels. This value is omitted then the scaling will + * based only on the width value. + * @param $upscale + * Boolean indicating that files smaller than the dimensions will be scalled + * up. This generally results in a low quality image. * @return * TRUE or FALSE, based on success. + * + * @see image_load() + * @see image_scale_and_crop() */ -function image_scale($source, $destination, $width, $height) { - $info = image_get_info($source); +function image_scale(stdClass $image, $width = NULL, $height = NULL, $upscale = FALSE) { + $aspect = $image->info['height'] / $image->info['width']; - // Don't scale up. - if ($width >= $info['width'] && $height >= $info['height']) { - return FALSE; + if ($upscale) { + // Set width/height according to aspect ratio if either is empty. + $width = !empty($width) ? $width : $height / $aspect; + $height = !empty($height) ? $height : $width / $aspect; + } + else { + // Set impossibly large values if the width and height aren't set. + $width = !empty($width) ? $width : 9999999; + $height = !empty($height) ? $height : 9999999; + + // Don't scale up. + if (round($width) >= $image->info['width'] && round($height) >= $image->info['height']) { + return TRUE; + } } - $aspect = $info['height'] / $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)); + return image_resize($image, $width, $height); } /** * 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_load(). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. - * @return - * TRUE or FALSE, based on success. - */ -function image_resize($source, $destination, $width, $height) { - return image_toolkit_invoke('resize', array($source, $destination, $width, $height)); -} - -/** - * 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 $degrees - * The number of (clockwise) degrees to rotate the image. - * @param $background - * An hexadecimal integer specifying the background color to use for the - * uncovered area of the image after the rotation. E.g. 0x000000 for black, - * 0xff00ff for magenta, and 0xffffff for white. + * @param $toolkit + * An optional override of the default image toolkit. * @return * TRUE or FALSE, based on success. + * + * @see image_load() */ -function image_rotate($source, $destination, $degrees, $background = 0x000000) { - return image_toolkit_invoke('rotate', array($source, $destination, $degrees, $background)); +function image_resize(stdClass $image, $width, $height) { + $width = (int) round($width); + $height = (int) round($height); + + return image_toolkit_invoke('resize', $image, array($width, $height)); } /** * 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_load(). * @param $x - * The top left co-ordinate, in pixels, of the crop area (x axis value). + * The top left coordinate, in pixels, 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 coordinate, in pixels, 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_load() + * @see image_scale_and_crop() + */ +function image_crop(stdClass $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', $image, array($x, $y, $width, $height)); +} + +/** + * Convert an image to grayscale. + * + * @param $image + * An image object returned by image_load(). + * @return + * TRUE or FALSE, based on success. + * + * @see image_load() + */ +function image_desaturate(stdClass $image) { + return image_toolkit_invoke('desaturate', $image); +} + + +/** + * Load an image file and return an image object. + * + * Any changes to the file are not saved until image_save() is called. + * + * @param $file + * Path to an image file. + * @param $toolkit + * An optional, image toolkit name to override the default. + * @return + * An image object or FALSE if there was a problem loading the file. The + * image object has the following properties: + * - 'source' - The original file path. + * - 'info' - The array of information returned by image_get_info() + * - 'toolkit' - The name of the image toolkit requested when the image was + * loaded. + * Image tookits may add additional properties. The caller is advised not to + * monkey about with them. + * + * @see image_save() + * @see image_get_info() + * @see image_get_available_toolkits() */ -function image_crop($source, $destination, $x, $y, $width, $height) { - return image_toolkit_invoke('crop', array($source, $destination, $x, $y, $width, $height)); +function image_load($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_toolkit_invoke('load', $image)) { + return $image; + } + } + return FALSE; +} + +/** + * Close the image and save the changes to a file. + * + * @param $image + * An image object returned by image_load(). The object's 'info' property + * will be updated if the file is saved successfully. + * @param $destination + * Destination path where the image should be saved. If it is empty the + * original image file will be overwritten. + * @return + * TRUE or FALSE, based on success. + * + * @see image_load() + */ +function image_save(stdClass $image, $destination = NULL) { + if (empty($destination)) { + $destination = $image->source; + } + if ($return = image_toolkit_invoke('save', $image, array($destination))) { + // Clear the cached file size and refresh the image information. + clearstatcache(); + $image->info = image_get_info($destination); + + if (@chmod($destination, 0664)) { + return $return; + } + watchdog('image', 'Could not set permissions on destination file: %file', array('%file' => $destination)); + } + return FALSE; } /** diff --git a/modules/simpletest/tests/image.test b/modules/simpletest/tests/image.test new file mode 100644 index 0000000000000000000000000000000000000000..2348b28e1c5fbc92639b19be59a777c3c6aa80ea --- /dev/null +++ b/modules/simpletest/tests/image.test @@ -0,0 +1,397 @@ +<?php +// $Id$ + +/** + * @file + * Unit tests for the Drupal Form API. + */ + +/** + * Base class for image manipulation testing. + */ +class ImageToolkitTestCase extends DrupalWebTestCase { + protected $toolkit; + protected $file; + protected $image; + + function getInfo() { + return array( + 'name' => t('Image toolkit tests'), + 'description' => t('Check image tookit functions.'), + 'group' => t('Image API'), + ); + } + + function setUp() { + parent::setUp('image_test'); + + // Use the image_test.module's test toolkit. + $this->toolkit = 'test'; + + // Pick a file for testing. + $this->file = $this->originalFileDirectory . '/simpletest/image-test.png'; + + // Setup a dummy image to work with, this replicate image_load() so we + // can avoid calling it. + $this->image = new stdClass(); + $this->image->source = $this->file; + $this->image->info = image_get_info($this->file); + $this->image->toolkit = $this->toolkit; + + // Clear out any hook calls. + image_test_reset(); + } + + /** + * Assert that all of the specified image toolkit operations were called + * exactly once once, other values result in failure. + * + * @param $expected + * Array with string containing with the operation name, e.g. 'load', + * 'save', 'crop', etc. + */ + function assertToolkitOperationsCalled(array $expected) { + // Determine which operations were called. + $actual = array_keys(array_filter(image_test_get_all_calls())); + + // Determine if there were any expected that were not called. + $uncalled = array_diff($expected, $actual); + if (count($uncalled)) { + $this->assertTrue(FALSE, t('Expected operations %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)))); + } + else { + $this->assertTrue(TRUE, t('All the expected operations were called: %expected', array('%expected' => implode(', ', $expected)))); + } + + // Determine if there were any unexpected calls. + $unexpected = array_diff($actual, $expected); + if (count($unexpected)) { + $this->assertTrue(FALSE, t('Unexpected operations were called: %unexpected.', array('%unexpected' => implode(', ', $unexpected)))); + } + else { + $this->assertTrue(TRUE, t('No unexpected operations were called.')); + } + } + + /** + * Check that hook_image_toolkits() is called and only available toolkits are + * returned. + */ + function testGetAvailableToolkits() { + $toolkits = image_get_available_toolkits(); + $this->assertTrue(isset($toolkits['test']), t('The working toolkit was returned.')); + $this->assertFalse(isset($toolkits['broken']), t('The toolkit marked unavailable was not returned')); + $this->assertToolkitOperationsCalled(array()); + } + + /** + * Test the image_load() function. + */ + function testLoad() { + $image = image_load($this->file, $this->toolkit); + $this->assertTrue(is_object($image), t('Returned an object.')); + $this->assertEqual($this->toolkit, $image->toolkit, t('Image had toolkit set.')); + $this->assertToolkitOperationsCalled(array('load')); + } + + /** + * Test the image_save() function. + */ + function testSave() { + $this->assertFalse(image_save($this->image), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('save')); + } + + /** + * Test the image_resize() function. + */ + function testResize() { + $this->assertTrue(image_resize($this->image, 1, 2), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('resize')); + + // Check the parameters. + $calls = image_test_get_all_calls(); + $this->assertEqual($calls['resize'][0][1], 1, t('Width was passed correctly')); + $this->assertEqual($calls['resize'][0][2], 2, t('Height was passed correctly')); + } + + /** + * Test the image_scale() function. + */ + function testScale() { +// TODO: need to test upscaling + $this->assertTrue(image_scale($this->image, 10, 10), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('resize')); + + // Check the parameters. + $calls = image_test_get_all_calls(); + $this->assertEqual($calls['resize'][0][1], 10, t('Width was passed correctly')); + $this->assertEqual($calls['resize'][0][2], 5, t('Height was based off aspect ratio and passed correctly')); + } + + /** + * Test the image_scale_and_crop() function. + */ + function testScaleAndCrop() { + $this->assertTrue(image_scale_and_crop($this->image, 5, 10), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('resize', 'crop')); + + // Check the parameters. + $calls = image_test_get_all_calls(); + + $this->assertEqual($calls['crop'][0][1], 7.5, t('X was computed and passed correctly')); + $this->assertEqual($calls['crop'][0][2], 0, t('Y was computed and passed correctly')); + $this->assertEqual($calls['crop'][0][3], 5, t('Width was computed and passed correctly')); + $this->assertEqual($calls['crop'][0][4], 10, t('Height was computed and passed correctly')); + } + + /** + * Test the image_crop() function. + */ + function testCrop() { + $this->assertTrue(image_crop($this->image, 1, 2, 3, 4), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('crop')); + + // Check the parameters. + $calls = image_test_get_all_calls(); + $this->assertEqual($calls['crop'][0][1], 1, t('X was passed correctly')); + $this->assertEqual($calls['crop'][0][2], 2, t('Y was passed correctly')); + $this->assertEqual($calls['crop'][0][3], 3, t('Width was passed correctly')); + $this->assertEqual($calls['crop'][0][4], 4, t('Height was passed correctly')); + } + + /** + * Test the image_desaturate() function. + */ + function testDesaturate() { + $this->assertTrue(image_desaturate($this->image), t('Function returned the expected value.')); + $this->assertToolkitOperationsCalled(array('desaturate')); + + // Check the parameters. + $calls = image_test_get_all_calls(); + $this->assertEqual(count($calls['desaturate'][0]), 1, t('Only the image was passed.')); + } +} + +/** + * Test the core GD image manipulation functions. + */ +class ImageToolkitGdTestCase extends DrupalWebTestCase { + // Colors that are used in testing. + protected $black = array(0, 0, 0, 0); + protected $red = array(255, 0, 0, 0); + protected $green = array(0, 255, 0, 0); + protected $blue = array(0, 0, 255, 0); + protected $yellow = array(255, 255, 0, 0); + protected $fuchsia = array(255, 0, 255, 0); // Used as background colors. + protected $transparent = array(0, 0, 0, 127); + protected $white = array(255, 255, 255, 0); + + protected $width = 40; + protected $height = 20; + + function getInfo() { + return array( + 'name' => t('Image GD manipulation tests'), + 'description' => t('Check that core image manipulations work properly: scale, resize, crop, scale and crop, and desaturate.'), + 'group' => t('Image API'), + ); + } + + /** + * Function to compare two colors by RGBa. + */ + function colorsAreEqual($color_a, $color_b) { + // Fully transparent pixels are equal, regardless of RGB. + if ($color_a[3] == 127 && $color_b[3] == 127) { + return TRUE; + } + + foreach ($color_a as $key => $value) { + if ($color_b[$key] != $value) { + return FALSE; + } + } + + return TRUE; + } + + /** + * Function for finding a pixel's RGBa values. + */ + function getPixelColor($image, $x, $y) { + $color_index = imagecolorat($image->resource, $x, $y); + + $transparent_index = imagecolortransparent($image->resource); + if ($color_index == $transparent_index) { + return array(0, 0, 0, 127); + } + + return array_values(imagecolorsforindex($image->resource, $color_index)); + } + + /** + * Since PHP can't visually check that our images have been manipulated + * properly, build a list of expected color values for each of the corners and + * the expected height and widths for the final images. + */ + function testManipulations() { + // If GD isn't available don't bother testing this. + if (!drupal_function_exists('image_gd_check_settings') || !image_gd_check_settings()) { + $this->pass(t('Image manipulations for the GD toolkit were skipped because the GD toolkit is not available.')); + return; + } + + // Typically the corner colors will be unchanged. These colors are in the + // order of top-left, top-right, bottom-right, bottom-left. + $default_corners = array($this->red, $this->green, $this->blue, $this->transparent); + + // A list of files that will be tested. + $files = array( + 'image-test.png', + 'image-test.gif', + 'image-test.jpg', + ); + + // Setup a list of tests to perform on each type. + $operations = array( + 'resize' => array( + 'function' => 'resize', + 'arguments' => array(20, 10), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'scale_x' => array( + 'function' => 'scale', + 'arguments' => array(20, NULL), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'scale_y' => array( + 'function' => 'scale', + 'arguments' => array(NULL, 10), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'upscale_x' => array( + 'function' => 'scale', + 'arguments' => array(80, NULL, TRUE), + 'width' => 80, + 'height' => 40, + 'corners' => $default_corners, + ), + 'upscale_y' => array( + 'function' => 'scale', + 'arguments' => array(NULL, 40, TRUE), + 'width' => 80, + 'height' => 40, + 'corners' => $default_corners, + ), + 'crop' => array( + 'function' => 'crop', + 'arguments' => array(12, 4, 16, 12), + 'width' => 16, + 'height' => 12, + 'corners' => array_fill(0, 4, $this->white), + ), + 'scale_and_crop' => array( + 'function' => 'scale_and_crop', + 'arguments' => array(10, 8), + 'width' => 10, + 'height' => 8, + 'corners' => array_fill(0, 4, $this->black), + ), + 'desaturate' => array( + 'function' => 'desaturate', + 'arguments' => array(), + 'height' => 20, + 'width' => 40, + // Grayscale corners are a bit funky. Each of the corners are a shade of + // gray. The values of these were determined simply by looking at the + // final image to see what desaturated colors end up being. + 'corners' => array(array_fill(0, 3, 76) + array(3 => 0), array_fill(0, 3, 149) + array(3 => 0), array_fill(0, 3, 29) + array(3 => 0), array_fill(0, 3, 0) + array(3 => 127)), + ), + ); + + foreach ($files as $file) { + foreach ($operations as $op => $values) { + // Load up a fresh image. + $image = image_load($this->originalFileDirectory . '/simpletest/' . $file, 'gd'); + if (!$image) { + $this->fail(t('Could not load image %file.', array('%file' => $file))); + continue 2; + } + + // Transparent GIFs and the imagefilter function don't work together. + // There is a todo in image.gd.inc to correct this. + if ($image->info['extension'] == 'gif') { + if ($op == 'desaturate') { + $values['corners'][3] = $this->white; + } + } + + // Perform our operation. + $function = 'image_'. $values['function']; + $arguments = array(); + $arguments[] = &$image; + $arguments = array_merge($arguments, $values['arguments']); + call_user_func_array($function, $arguments); + + // To keep from flooding the test with assert values, make a general + // value for whether each group of values fail. + $correct_dimensions_real = TRUE; + $correct_dimensions_object = TRUE; + $correct_colors = TRUE; + + // Check the real dimensions of the image first. + if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) { + $correct_dimensions_real = FALSE; + } + + // Check that the image object has an accurate record of the dimensions. + if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) { + $correct_dimensions_object = FALSE; + } + // Now check each of the corners to ensure color correctness. + foreach ($values['corners'] as $key => $corner) { + // Get the location of the corner. + switch ($key) { + case 0: + $x = 0; + $y = 0; + break; + case 1: + $x = $values['width'] - 1; + $y = 0; + break; + case 2: + $x = $values['width'] - 1; + $y = $values['height'] - 1; + break; + case 3: + $x = 0; + $y = $values['height'] - 1; + break; + } + $color = $this->getPixelColor($image, $x, $y); + $correct_colors = $this->colorsAreEqual($color, $corner); + } + + $directory = file_directory_path() . '/imagetests'; + file_check_directory($directory, FILE_CREATE_DIRECTORY); + image_save($image, $directory . '/' . $op . '.' . $image->info['extension']); + + $this->assertTrue($correct_dimensions_real, t('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op))); + $this->assertTrue($correct_dimensions_object, t('Image %file object after %action action is reporting the proper height and width values.', array('%file' => $file, '%action' => $op))); + // JPEG colors will always be messed up due to compression. + if ($image->info['extension'] != 'jpg') { + $this->assertTrue($correct_colors, t('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op))); + } + } + } + + } +} diff --git a/modules/simpletest/tests/image_test.info b/modules/simpletest/tests/image_test.info new file mode 100644 index 0000000000000000000000000000000000000000..fb1545d5c9d8cce300ee716681bbbe98b34983d7 --- /dev/null +++ b/modules/simpletest/tests/image_test.info @@ -0,0 +1,8 @@ +; $Id$ +name = "Image test" +description = "Support module for image toolkit tests." +package = Testing +version = VERSION +core = 7.x +files[] = image_test.module +hidden = TRUE diff --git a/modules/simpletest/tests/image_test.module b/modules/simpletest/tests/image_test.module new file mode 100644 index 0000000000000000000000000000000000000000..07f59461d88aed441c1c943a20af15889b3f27f5 --- /dev/null +++ b/modules/simpletest/tests/image_test.module @@ -0,0 +1,121 @@ +<?php +// $Id$ + +/** + * @file + * Helper module for the image tests. + */ + +/** + * Implementation of hook_image_toolkits(). + */ +function image_test_image_toolkits() { + return array( + 'test' => array( + 'title' => t('A dummy toolkit that works'), + 'available' => TRUE, + ), + 'broken' => array( + 'title' => t('A dummy toolkit that is "broken"'), + 'available' => FALSE, + ), + ); +} + +/** + * Reset/initialize the history of calls to the toolkit functions. + * + * @see image_test_get_all_calls(). + */ +function image_test_reset() { + // Keep track of calls to these operations + $results = array( + 'load' => array(), + 'save' => array(), + 'settings' => array(), + 'resize' => array(), + 'crop' => array(), + 'desaturate' => array(), + ); + variable_set('image_test_results', $results); +} + +/** + * Get an array with the all the calls to the toolkits since image_test_reset() + * was called. + * + * @return + * An array keyed by operation name ('load', 'save', 'settings', 'resize', + * 'crop', 'desaturate') with values being arrays of parameters passed to + * each call. + */ +function image_test_get_all_calls() { + return variable_get('image_test_results', array()); +} + +/** + * Store the values passed to a toolkit call. + * + * @param $op + * One of the image toolkit operations: 'load', 'save', 'settings', 'resize', + * 'crop', 'desaturate'. + * @param $args + * Values passed to hook. + * @see image_test_get_all_calls() + * @see image_test_reset() + */ +function _image_test_log_call($op, $args) { + $results = variable_get('image_test_results', array()); + $results[$op][] = $args; + variable_set('image_test_results', $results); +} + +/** + * Image tookit's settings operation. + */ +function image_test_settings() { + _image_test_log_call('settings', array()); + return array(); +} + +/** + * Image tookit's load operation. + */ +function image_test_load(stdClass $image) { + _image_test_log_call('load', array($image)); + return $image; +} + +/** + * Image tookit's save operation. + */ +function image_test_save(stdClass $image, $destination) { + _image_test_log_call('save', array($image, $destination)); + // Return false so that image_save() doesn't try to chmod the destination + // file that we didn't bother to create. + return FALSE; +} + +/** + * Image tookit's crop operation. + */ +function image_test_crop(stdClass $image, $x, $y, $width, $height) { + _image_test_log_call('crop', array($image, $x, $y, $width, $height)); + return TRUE; +} + +/** + * Image tookit's resize operation. + */ +function image_test_resize(stdClass $image, $width, $height) { + _image_test_log_call('resize', array($image, $width, $height)); + return TRUE; +} + +/** + * Image tookit's desaturate operation. + */ +function image_test_desaturate(stdClass $image) { + _image_test_log_call('desaturate', array($image)); + return TRUE; +} diff --git a/modules/system/image.gd.inc b/modules/system/image.gd.inc index 03808d7c4759890ea48c5b6c1abe56d8c141bf58..2ba31bbc65e69d9891b57106d5acf43a7462bde4 100644 --- a/modules/system/image.gd.inc +++ b/modules/system/image.gd.inc @@ -11,13 +11,6 @@ * @{ */ -/** - * Retrieve information about the toolkit. - */ -function image_gd_info() { - return array('name' => 'gd', 'title' => t('GD2 image manipulation toolkit')); -} - /** * Retrieve settings for the GD2 toolkit. */ @@ -76,146 +69,176 @@ function image_gd_check_settings() { /** * Scale an image to the specified size using GD. + * + * @param $image + * An image object. The $image->resource, $image->info['width'], and + * $image->info['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. + * @return + * TRUE or FALSE, based on success. + * + * @see image_resize() */ -function image_gd_resize($source, $destination, $width, $height) { - if (!file_exists($source)) { - return FALSE; - } +function image_gd_resize(stdClass $image, $width, $height) { + $res = image_gd_create_tmp($image, $width, $height); - $info = image_get_info($source); - if (!$info) { + if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) { return FALSE; } - $im = image_gd_open($source, $info['extension']); - if (!$im) { - 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->resource); + // Update image object. + $image->resource = $res; + $image->info['width'] = $width; + $image->info['height'] = $height; + return TRUE; } /** - * Rotate an image the given number of degrees. + * Crop an image using the GD toolkit. + * + * @param $image + * An image object. The $image->resource, $image->info['width'], and + * $image->info['height'] values will be modified by this call. + * @param $x + * The starting x offset at which to start the crop, in pixels. + * @param $y + * The starting y offset at which to start the crop, in pixels. + * @param $width + * The width of the cropped area, in pixels. + * @param $height + * The height of the cropped area, in pixels. + * @return + * TRUE or FALSE, based on success. + * + * @see image_crop() */ -function image_gd_rotate($source, $destination, $degrees, $background = 0x000000) { - if (!function_exists('imageRotate')) { - return FALSE; - } - - $info = image_get_info($source); - if (!$info) { - return FALSE; - } +function image_gd_crop(stdClass $image, $x, $y, $width, $height) { + $res = image_gd_create_tmp($image, $width, $height); - $im = image_gd_open($source, $info['extension']); - if (!$im) { + if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) { return FALSE; } - $res = imageRotate($im, $degrees, $background); - $result = image_gd_close($res, $destination, $info['extension']); - - return $result; + // Destroy the original image and return the modified image. + imagedestroy($image->resource); + $image->resource = $res; + $image->info['width'] = $width; + $image->info['height'] = $height; + return TRUE; } /** - * Crop an image using the GD toolkit. + * Convert an image resource to grayscale. + * + * Note that transparent GIFs loose transparency when desaturated. + * + * @param $image + * An image object. The $image->resource value will be modified by this call. + * @return + * TRUE or FALSE, based on success. + * + * @see image_desaturate() */ -function image_gd_crop($source, $destination, $x, $y, $width, $height) { - $info = image_get_info($source); - if (!$info) { - 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; +function image_gd_desaturate(stdClass $image) { + return imagefilter($image->resource, 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->resource value will populated by this call. * @return - * An image resource, or FALSE on error. + * TRUE or FALSE, based on success. + * + * @see image_load() */ -function image_gd_open($file, $extension) { - $extension = str_replace('jpg', 'jpeg', $extension); - $open_func = 'imageCreateFrom' . $extension; - if (!function_exists($open_func)) { - return FALSE; - } - return $open_func($file); +function image_gd_load(stdClass $image) { + $extension = str_replace('jpg', 'jpeg', $image->info['extension']); + $function = 'imagecreatefrom'. $extension; + return (function_exists($function) && $image->resource = $function($image->source)); } /** * 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. + * TRUE or FALSE, based on success. + * + * @see image_save() */ -function image_gd_close($res, $destination, $extension) { - $extension = str_replace('jpg', 'jpeg', $extension); - $close_func = 'image' . $extension; - if (!function_exists($close_func)) { +function image_gd_save(stdClass $image, $destination) { + $extension = str_replace('jpg', 'jpeg', $image->info['extension']); + $function = 'image'. $extension; + if (!function_exists($function)) { return FALSE; } if ($extension == 'jpeg') { - return $close_func($res, $destination, variable_get('image_jpeg_quality', 75)); + return $function($image->resource, $destination, variable_get('image_jpeg_quality', 75)); } else { - return $close_func($res, $destination); + // Always save PNG images with full transparency. + if ($extension == 'png') { + imagealphablending($image->resource, FALSE); + imagesavealpha($image->resource, TRUE); + } + return $function($image->resource, $destination); } } +/** + * Create a truecolor image preserving transparency from a provided image. + * + * @param $image + * An image object. + * @param $width + * The new width of the new image, in pixels. + * @param $height + * The new height of the new image, in pixels. + * @return + * A GD image handle. + */ +function image_gd_create_tmp(stdClass $image, $width, $height) { + $res = imagecreatetruecolor($width, $height); + + if ($image->info['extension'] == 'gif') { + // Grab transparent color index from image resource. + $transparent = imagecolortransparent($image->resource); + + if ($transparent >= 0) { + // The original must have a transparent color, allocate to the new image. + $transparent_color = imagecolorsforindex($image->resource, $transparent); + $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); + + // Flood with our new transparent color. + imagefill($res, 0, 0, $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); + } + else { + imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255)); + } + + return $res; +} + /** * @} End of "ingroup image". */ diff --git a/modules/system/system.admin.inc b/modules/system/system.admin.inc index ecc15e3a8a9f05c34c0a27d8bc2e7ab805f0de23..2e24cf8d36245bc28dbf46967baa11a3bb7e8ccc 100644 --- a/modules/system/system.admin.inc +++ b/modules/system/system.admin.inc @@ -1462,19 +1462,33 @@ function system_file_system_settings() { */ function system_image_toolkit_settings() { $toolkits_available = image_get_available_toolkits(); + $current_toolkit = image_get_toolkit(); + + if (count($toolkits_available) == 0) { + variable_del('image_toolkit'); + $form['image_toolkit_help'] = array( + '#markup' => t("No image toolkits were detected. Drupal includes support for <a href='!gd-link'>PHP's built-in image processing functions</a> but they were not detected on this system. You should consult your system administrator to have them enabled, or try using a third party toolkit.", array('gd-link' => url('http://php.net/gd'))), + ); + return $form; + } + if (count($toolkits_available) > 1) { $form['image_toolkit'] = array( '#type' => 'radios', '#title' => t('Select an image processing toolkit'), - '#default_value' => image_get_toolkit(), + '#default_value' => $current_toolkit, '#options' => $toolkits_available ); } - elseif (count($toolkits_available) == 1) { + else { variable_set('image_toolkit', key($toolkits_available)); } - $form['image_toolkit_settings'] = image_toolkit_invoke('settings'); + // Get the toolkit's settings form. + $function = 'image_' . $current_toolkit . '_settings'; + if (drupal_function_exists($function)) { + $form['image_toolkit_settings'] = $function(); + } return system_settings_form($form, TRUE); } diff --git a/modules/system/system.api.php b/modules/system/system.api.php index 8bdace6425972f3d1f60120263d0fc06ad84a93a..7e77e7dcda5c8eda2742a5805930027060c75a42 100644 --- a/modules/system/system.api.php +++ b/modules/system/system.api.php @@ -365,17 +365,40 @@ function hook_init() { } /** -* Define image toolkits provided by this module. -* -* The file which includes each toolkit's functions must be declared as part of -* the files array in the module .info file so that the registry will find and -* parse it. -* -* @return -* An array of image toolkit names. -*/ + * Define image toolkits provided by this module. + * + * The file which includes each toolkit's functions must be declared as part of + * the files array in the module .info file so that the registry will find and + * parse it. + * + * The toolkit's functions must be named image_toolkitname_operation(). + * where the operation may be: + * - 'load': Required. See image_gd_load() for usage. + * - 'save': Required. See image_gd_save() for usage. + * - 'settings': Optional. See image_gd_settings() for usage. + * - 'resize': Optional. See image_gd_resize() for usage. + * - 'crop': Optional. See image_gd_crop() for usage. + * - 'desaturate': Optional. See image_gd_desaturate() for usage. + * + * @return + * An array with the toolkit name as keys and sub-arrays with these keys: + * - 'title': A string with the toolkit's title. + * - 'available': A Boolean value to indicate that the toolkit is operating + * properly, e.g. all required libraries exist. + * + * @see system_image_toolkits() + */ function hook_image_toolkits() { - return array('gd'); + return array( + 'working' => array( + 'title' => t('A toolkit that works.'), + 'available' => TRUE, + ), + 'broken' => array( + 'title' => t('A toolkit that is "broken" and will not be listed.'), + 'available' => FALSE, + ), + ); } /** diff --git a/modules/system/system.module b/modules/system/system.module index 3ea855985ea45144267ba82386771843d9cafa44..7f259ad87f900c2a7fa145c9c51468e9bb122520 100644 --- a/modules/system/system.module +++ b/modules/system/system.module @@ -2290,5 +2290,10 @@ function theme_meta_generator_header($version = VERSION) { * Implementation of hook_image_toolkits(). */ function system_image_toolkits() { - return array('gd'); + return array( + 'gd' => array( + 'title' => t('GD2 image manipulation toolkit'), + 'available' => drupal_function_exists('image_gd_check_settings') && image_gd_check_settings(), + ), + ); }