You are here

function file_validate_is_image in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/file/file.module \file_validate_is_image()
  2. 6 includes/file.inc \file_validate_is_image()
  3. 7 includes/file.inc \file_validate_is_image()
  4. 10 core/modules/file/file.module \file_validate_is_image()

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()

1 call to file_validate_is_image()
ValidatorTest::testFileValidateIsImage in core/modules/file/tests/src/Kernel/ValidatorTest.php
This ensures a specific file is actually an image.

File

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

Code

function file_validate_is_image(FileInterface $file) {
  $errors = [];
  $image_factory = \Drupal::service('image.factory');
  $image = $image_factory
    ->get($file
    ->getFileUri());
  if (!$image
    ->isValid()) {
    $supported_extensions = $image_factory
      ->getSupportedExtensions();
    $errors[] = t('The image file is invalid or the image type is not allowed. Allowed types: %types', [
      '%types' => implode(', ', $supported_extensions),
    ]);
  }
  return $errors;
}