0

I want to get the file entity out of an media image bundle to the get the filename to check if the image is cmyk or not.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function hook_media_presave(MediaInterface $entity) {
  if ($entity->bundle() == 'image') {
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($field_definitions as $field_definition) {
      if ($field_definition->getType() 'image') {
        // get File entity here.
      }
    }
  }
}

How do I do this?

0

I've found a solution.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function hook_media_presave(MediaInterface $entity) {
  if ($entity->bundle() == 'image') {
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($field_definitions as $field_definition) {
      if ($field_definition->getType() == 'image') {
        /** @var FieldItemListInterface $field_value */
        $field_values = $entity->get($field_definition->getName())->getValue();
        if (is_array($field_values)) {
          foreach ($field_values as $field_value) {
            if ($field_value['target_id']) {
              /** @var File $file */
              $file = File::load($field_value['target_id']);
              $image = getimagesize($file->getFileUri());
              // If the image has channels '4' it is cmyk.
              if ($image['channels'] == '4') {
                $imagick = new Imagick($file->getFileUri());
                $imagick->setImageColorspace(Imagick::COLORSPACE_RGB);
                $imagick->writeImage($image);
                $imagick->destroy();
              }
            }
          }
        }
      }
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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