MaxSizeCropImageEffect.php in Image max size crop 8        
                          
                  
                        
  
  
  
  
  
File
  src/Plugin/ImageEffect/MaxSizeCropImageEffect.php
  
    View source  
  <?php
namespace Drupal\image_max_size_crop\Plugin\ImageEffect;
use Drupal\Core\Image\ImageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Plugin\ImageEffect\CropImageEffect;
class MaxSizeCropImageEffect extends CropImageEffect {
  
  public function applyEffect(ImageInterface $image) {
    
    $original_width = $this->configuration['width'];
    if (!$this->configuration['width'] || $this->configuration['width'] > $image
      ->getWidth()) {
      $this->configuration['width'] = $image
        ->getWidth();
    }
    
    $original_height = $this->configuration['height'];
    if (!$this->configuration['height'] || $this->configuration['height'] > $image
      ->getHeight()) {
      $this->configuration['height'] = $image
        ->getHeight();
    }
    $result = parent::applyEffect($image);
    
    $this->configuration['width'] = $original_width;
    $this->configuration['height'] = $original_height;
    return $result;
  }
  
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    unset($form['width']['#required']);
    unset($form['height']['#required']);
    return $form;
  }
  
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
    if ($form_state
      ->isValueEmpty('width') && $form_state
      ->isValueEmpty('height')) {
      $form_state
        ->setErrorByName('data', $this
        ->t('Width and height can not both be blank.'));
    }
  }
}