You are here

function entity_browser_file_validate_image_resolution in Entity Browser 8.2

Same name and namespace in other branches
  1. 8 entity_browser.module \entity_browser_file_validate_image_resolution()

Validates image resolution for the given File.

Drupal core does not allow users to use existing images. As a result, calling the normal file_validate_image_resolution() function on a file that may be used elsewhere would resize it for all of its uses. We copy the normal validation here so that we can stop this from occurring.

Parameters

\Drupal\file\FileInterface $file: The file being evaluated.

int $maximum_dimensions: The maximum dimensions.

int $minimum_dimensions: The minimum dimensions.

Return value

array See file_validate_image_resolution()

File

./entity_browser.module, line 138
Allows to flexibly create, browse and select entities.

Code

function entity_browser_file_validate_image_resolution(FileInterface $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  $errors = [];

  // 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.
        // This $file->isPermanent() check is the only part of the function
        // body that is significantly different.
        if (!$file
          ->isPermanent() && $image
          ->scale($width, $height)) {
          $image
            ->save();
          $file->filesize = $image
            ->getFileSize();
          \Drupal::messenger()
            ->addMessage(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', [
            '%dimensions' => $maximum_dimensions,
          ]));
        }
        else {
          $errors[] = t('The image exceeds the maximum allowed dimensions.');
        }
      }
    }
    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.', [
          '%dimensions' => $minimum_dimensions,
        ]);
      }
    }
  }
  return $errors;
}