Score:0

Extract image meta data and set field values on Media upload

ec flag
Tim

I'm extracting IPTC and EXIF data when the user uploads an image using the Media Library UI.

Using hook_form_alter I can get the URI of the uploaded file in the media_library_add_form_upload form, and extract the data from it. So far, so good.

However, the form does not (yet?) contain the other fields attached to the media type (e.g. title, description, copyright) so I can't set the values.

How can I set the values in the form that is shown after I've selected and upload an image?

Score:0
ec flag
Tim

The form fields are nested under $form['media'][0]. Having extracted data from the uploaded file, we can set the data as default values on the fields.

/**
 * Implements hook_media_form_alter().
 */
function ds_media_exif_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id !== 'media_library_add_form_upload') {
    return;
  }

  if (!array_key_exists('upload', $values)) {
    return;
  }

  $upload_id = $values['upload'][0];
  $file = File::load($upload_id);
  $uri = $file->getFileUri();

  // Extract exif, iptc data here.
  $data = extractFileData($uri);

  // Title defaults to the file name.
  if (isset($data['title'])) {
    $form['media'][0]['fields']['name']['widget'][0]['value']['#default_value'] = $data['title'];
    // Set alt field to title.
    $form['media'][0]['fields']['field_media_image']['widget'][0]['#default_value']['alt'] = $data['title'];
  }

  // Some more fields: field_description and field_copyright.
  $form['media'][0]['fields']['field_description']['widget'][0]['#default_value'] = $data['description'] ?: '';
  $form['media'][0]['fields']['field_copyright']['widget'][0]['value']['#default_value'] = $data['copyright'] ?: '';
}
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.