Calling script on image upload in Drupal

2019-08-02 06:03发布

I would like to call a Ruby script when a user uploads an image to my Drupal content-type. I have a CCK image field that serves as the main image, and ImageCache takes care of resizing and creating thumbnails for me.

I have a Ruby script that does some transformations to the image, however I don't exactly know how to call it (no experience with Ruby really). Basically the script applies some image transforms and then generates a new image.

My question is how to call this script from Drupal...is there some sort of hook regarding the CCK image upload that I would hijack?

1条回答
狗以群分
2楼-- · 2019-08-02 06:42

ImageField uses the same API as FileField. Therefore, you could add a custom validator for your upload field, which would do some checks on the image (like calling a ruby script).

I described that some time ago on Drupal.org, see: http://drupal.org/node/546146

However, for your convenience, here the code.

First, define a validator for the upload form:

function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'ID_OF_YOUR_FORM')
    return;

  $form['FIELDNAME'][0]['#upload_validators']['example_FUNCTIONNAME'] = array();

  return $form;
}

Second, implement the validator function:

function example_FUNCTIONNAME($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field
  $filepath = $field->filepath;

  ...

  // in case of error, add error message
  $errors[] = t('Validation failed, because...');

  return $errors;
}

Put this code in a custom module, but make sure that your module is called after FileField and ImageField (adjust weight in system table).

Update: There is another way to hook into it. You can use hook_nodeapi to react on operation "presave". This also allows you to call a script on the content of the uploaded field.

查看更多
登录 后发表回答