function filefield_validate_image_resolution in FileField 6.3
An #upload_validators callback. Check an image resolution.
Parameters
$file: A Drupal file object.
$max_size: A string in the format WIDTHxHEIGHT. If the image is larger than this size the image will be scaled to fit within these dimensions.
$min_size: A string in the format WIDTHxHEIGHT. If the image is smaller than this size a validation error will be returned.
Return value
An array of any errors cause by this file if it failed validation.
File
- ./
filefield.module, line 842 - FileField: Defines a CCK file field type.
Code
function filefield_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
$errors = array();
@(list($max_width, $max_height) = explode('x', $maximum_dimensions));
@(list($min_width, $min_height) = explode('x', $minimum_dimensions));
// Check first that the file is an image.
if ($info = image_get_info($file->filepath)) {
if ($maximum_dimensions) {
$resized = FALSE;
// Check that it is smaller than the given dimensions.
if ($info['width'] > $max_width || $info['height'] > $max_height) {
$ratio = min($max_width / $info['width'], $max_height / $info['height']);
// Check for exact dimension requirements (scaling allowed).
if (strcmp($minimum_dimensions, $maximum_dimensions) == 0 && $info['width'] / $max_width != $info['height'] / $max_height) {
$errors[] = t('The image must be exactly %dimensions pixels.', array(
'%dimensions' => $maximum_dimensions,
));
}
elseif ((image_get_toolkit() || module_exists('imageapi')) && ($info['width'] * $ratio < $min_width || $info['height'] * $ratio < $min_height)) {
$errors[] = t('The image will not fit between the dimensions of %min_dimensions and %max_dimensions pixels.', array(
'%min_dimensions' => $minimum_dimensions,
'%max_dimensions' => $maximum_dimensions,
));
}
elseif (module_exists('imageapi') && imageapi_default_toolkit()) {
$res = imageapi_image_open($file->filepath);
imageapi_image_scale($res, $max_width, $max_height);
imageapi_image_close($res, $file->filepath);
$resized = TRUE;
}
elseif (image_get_toolkit() && @image_scale($file->filepath, $file->filepath, $max_width, $max_height)) {
$resized = TRUE;
}
else {
$errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array(
'%dimensions' => $maximum_dimensions,
));
}
}
// Clear the cached filesize and refresh the image information.
if ($resized) {
drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array(
'%dimensions' => $maximum_dimensions,
)));
clearstatcache();
$file->filesize = filesize($file->filepath);
}
}
if ($minimum_dimensions && empty($errors)) {
// Check that it is larger than the given dimensions.
if ($info['width'] < $min_width || $info['height'] < $min_height) {
$errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array(
'%dimensions' => $minimum_dimensions,
));
}
}
}
return $errors;
}