0

With the core media Image type, I want to restrict uploaded images by aspect ratio.

I want to block images that have the wrong aspect ratio from being uploaded. My question is the same as this Drupal 7 question, but for Drupal 8+.

1 Answer 1

0

This helpful blog post gave me an answer:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'media_image_add_form':
    case 'media_image_edit_form':
      $form['field_media_image']['widget'][0]['#upload_validators']['_validate_image_aspect_ratio'] = [];
      break;
  }
}

/**
 * Ensures that images have a square aspect ratio.
 *
 * @param \Drupal\file\FileInterface $file
 *   File object.
 *
 * @return array
 *   Errors array.
 */
function _validate_image_aspect_ratio(FileInterface $file) {
  $errors = [];
  $image = \Drupal::service('image.factory')->get($file->getFileUri());
  if ($image->isValid()) {
    // Add your condition validations here!
    $width = $image->getWidth();
    $height = $image->getHeight();
    $aspect_ratio = $width / $height;
    if ($aspect_ratio != 1 / 1) {
      $errors[] = t("The image should be a square!");
    }
  }
  return $errors;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.