Score:0

How to enforce a specific aspect ratio for all Media images?

cn flag

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+.

Score:0
cn flag

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;
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.