function file_validate_image_resolution in Zircon Profile 8.0
Same name and namespace in other branches
- 8 core/modules/file/file.module \file_validate_image_resolution()
Verifies that image dimensions are within the specified maximum and minimum.
Non-image files will be ignored. If an image toolkit is available the image will be scaled to fit within the desired maximum dimensions.
Parameters
\Drupal\file\FileInterface $file: A file entity. This function may resize the file affecting its size.
string $maximum_dimensions: An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If an image toolkit is installed the image will be resized down to these dimensions. A value of 0 indicates no restriction on size, so resizing will be attempted.
string $minimum_dimensions: An optional string in the form WIDTHxHEIGHT. This will check that the image meets a minimum size. A value of 0 indicates no restriction.
Return value
An array. If the file is an image and did not meet the requirements, it will contain an error message.
See also
1 call to file_validate_image_resolution()
- ValidatorTest::testFileValidateImageResolution in core/
modules/ file/ src/ Tests/ ValidatorTest.php - This ensures the resolution of a specific file is within bounds. The image will be resized if it's too large.
File
- core/
modules/ file/ file.module, line 423 - Defines a "managed_file" Form API field and a "file" field for Field module.
Code
function file_validate_image_resolution(FileInterface $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
$errors = array();
// Check first that the file is an image.
$image_factory = \Drupal::service('image.factory');
$image = $image_factory
->get($file
->getFileUri());
if ($image
->isValid()) {
if ($maximum_dimensions) {
// Check that it is smaller than the given dimensions.
list($width, $height) = explode('x', $maximum_dimensions);
if ($image
->getWidth() > $width || $image
->getHeight() > $height) {
// Try to resize the image to fit the dimensions.
if ($image
->scale($width, $height)) {
$image
->save();
$file->filesize = $image
->getFileSize();
drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array(
'%dimensions' => $maximum_dimensions,
)));
}
else {
$errors[] = t('The image exceeds the maximum allowed dimensions and an attempt to resize it failed.');
}
}
}
if ($minimum_dimensions) {
// Check that it is larger than the given dimensions.
list($width, $height) = explode('x', $minimum_dimensions);
if ($image
->getWidth() < $width || $image
->getHeight() < $height) {
$errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array(
'%dimensions' => $minimum_dimensions,
));
}
}
}
return $errors;
}