Skip to content

Instantly share code, notes, and snippets.

@QuentinFonteneau
Last active March 22, 2018 10:31
Show Gist options
  • Save QuentinFonteneau/91fd0fea12e8bab3a2394fb3a0b4ed11 to your computer and use it in GitHub Desktop.
Save QuentinFonteneau/91fd0fea12e8bab3a2394fb3a0b4ed11 to your computer and use it in GitHub Desktop.
Generate crop automatically
/**
* This function will generate crop automatically.
*
* This makes it possible to generate the crops automatically
* if the contributor forgets to do so.
*/
function _generate_crop_auto($form, $form_state) {
// Retrieve crop list.
$crop_list = $form['field_image']['widget'][0]['image_crop']['#crop_type_list'];
foreach ($crop_list as $crop) {
$crop_applied = $form_state->getValue('field_image')[0]['image_crop']['crop_wrapper'][$crop]['crop_container']['values']['crop_applied'];
// If crop isn't apply manually by contributor.
if ($crop_applied == '0') {
$media = Media::load($form_state->getValue('id'));
$cropType = CropType::load($crop);
list ($width_ratio, $height_ratio) = explode(':', $cropType->aspect_ratio);
// Define properties according to dimensions and ratio.
if ($width_ratio > $height_ratio) {
$properties['width'] = $media->field_image->width;
$properties['height'] = $media->field_image->width * $height_ratio / $width_ratio;
$properties['x'] = 0;
$properties['y'] = ($media->field_image->height - $properties['height']) / 2;
}
else {
$properties['height'] = $media->field_image->height;
$properties['width'] = $media->field_image->height * $width_ratio / $height_ratio;
$properties['x'] = ($media->field_image->width - $properties['width']) / 2;
$properties['y'] = 0;
}
$field_value = [
'file-uri' => $media->field_image->entity->uri->value,
'file-id' => $media->field_image->entity->fid->value,
];
$service = Drupal::service('image_widget_crop.manager');
$service->applyCrop($properties, $field_value, $cropType);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment