How to set a minimum width requirement on ckeditor image uploads in Drupal 8

Setting a minimum image width isn’t an option in the current UI configurations for the image upload widget in CKEditor, so it needs to be done with code. Below is code that sets a 1200px minimum width requirement on the image upload widget in ckeditor.

When images are being displayed at 100% screen width it’s necessary to require users to upload large images to prevent blurry, upscaled images.

General steps

  1. Define a hook_form_FORM_ID_alter function in a custom module.

  2. Load the text formatter we want to work with. In this case we load the the ‘full_html’ format. Change this if you want to apply the minimum width settings to a different format.

  3. Load the editor and get current upload settings.

  4. Set a variable that replicates the current maximum dimension settings (these can be set in the Drupal UI at Configuration > Content Authoring > Text formats and editors)

  5. Define the min dimensions as a string in the format of min_widthxmin_height, ex “1200x1”

  6. Set the new min and max dimensions of the upload validator

 

/*
* implements hook_form_FORM_ID_alter
* Add a field description and minimum image width to image upload ckeditor dialogs
* (Last tested on Drupal 8.6.7)
*/

function custom_mods_form_editor_image_dialog_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {


  // Get the Full HTML text format

  $filter_format = Drupal\filter\Entity\FilterFormat::load('full_html');



  // Load full html editor and get image upload settings, specifically dimensions

  $editor = editor_load($filter_format->id());

  $image_upload = $editor->getImageUploadSettings();

  if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {

      $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];

  }

  else {

      $max_dimensions = 0;

  }



  // Image min dimensions for this site should be 1200px wide

  // Min isn't an available field in the editor settings so we set it manually

  $min_dimensions = '1200x1';



  // Add the new settings to the actual image upload form

  $form['fid']['#description'] = t('Minimum image upload width: 1200px.');

  $form['fid']['#upload_validators']['file_validate_image_resolution'] = array($max_dimensions, $min_dimensions);


}