file_validate_is_image

file_validate_is_image(FileInterface $file)

Checks that the file is recognized as a valid image.

Parameters

\Drupal\file\FileInterface $file: A file entity.

Return value

array An empty array if the file is a valid image or an array containing an error message if it's not.

See also

hook_file_validate()

File

core/modules/file/file.module, line 392
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

1
2
3
4
5
6
7
8
9
10
11
12
function file_validate_is_image(FileInterface $file) {
  $errors = array();
 
  $image_factory = \Drupal::service('image.factory');
  $image = $image_factory->get($file->getFileUri());
  if (!$image->isValid()) {
    $supported_extensions = $image_factory->getSupportedExtensions();
    $errors[] = t('Image type not supported. Allowed types: %types', array('%types' => implode(' ', $supported_extensions)));
  }
 
  return $errors;
}
doc_Drupal
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.