You are here

imce_watermark.module in IMCE Watermark 7

Same filename and directory in other branches
  1. 6.2 imce_watermark.module

Adding watermark at IMCE image uploading.

File

imce_watermark.module
View source
<?php

/**
 * @file 
 * 
 * Adding watermark at IMCE image uploading.
 * 
 */

/**
 * Implements hook_permission().
 */
function imce_watermark_permission() {
  return array(
    'imce watermark control' => array(
      'title' => t('Control watermark'),
      'description' => t('Checkbox appear for controlling watermark at file uploading.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function imce_watermark_menu() {
  $items = array();
  $items['admin/config/media/imce/imce'] = array(
    'title' => 'IMCE',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/media/imce/imce_watermark'] = array(
    'title' => 'IMCE Watermark settings',
    'description' => 'Control how to apply watermark.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'imce_watermark_settings',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * imce_watermark settings form.
 */
function imce_watermark_settings($form, &$form_state) {
  $form = array();
  $form['#tree'] = TRUE;
  $form_state['profile'] = variable_get('imce_watermark_setting');
  $form_state['imce_watermark_common_setting'] = TRUE;
  imce_watermark_form_imce_profile_form_alter($form, $form_state, 'imce_profile_form');
  $form['#validate'][] = 'imce_watermark_settings_validate';
  $form['#submit'][] = 'imce_watermark_settings_submit';
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function imce_watermark_form_imce_profile_form_alter(&$form, &$form_state, $form_id) {
  $profile = $form_state['profile'];
  $common_setting = isset($form_state['imce_watermark_common_setting']) ? $form_state['imce_watermark_common_setting'] : FALSE;
  drupal_add_js('
(function ($) {
  $("select#edit-profile-imce-watermark-imagecache-preset").change(function() {
    if ($(this).val() == "-2") {
      if ($("#edit-profile-imce-watermark-custom").is(".collapsed")) {
        Drupal.toggleFieldset("#edit-profile-imce-watermark-custom");
      }
    }
    else {
      if (!$("#edit-profile-imce-watermark-custom").is(".collapsed")) {
        Drupal.toggleFieldset("#edit-profile-imce-watermark-custom");
      }
    }
  }).trigger("change");
})(jQuery);', array(
    'type' => 'inline',
    'scope' => 'footer',
  ));
  $presets = array();
  if (!$common_setting) {
    $presets[0] = ' - ' . t('Common settings') . ' - ';
  }
  $presets[-1] = ' - ' . t('Watermark disabled') . ' - ';
  $presets[-2] = ' - ' . t('Manual script watermark') . ' - ';
  if (module_exists('imagecache_canvasactions')) {
    $presets[t('Image styles')] = array();
    $styles = image_styles();
    foreach ($styles as $name => $style) {
      foreach ($style['effects'] as $effect) {
        if ($effect['name'] == 'canvasactions_file2canvas') {
          $presets[t('Image styles')][$name] = $style['name'];
          break;
        }
      }
    }
    if (empty($presets[t('Image styles')])) {
      unset($presets[t('Image styles')]);
    }
  }
  $selected_preset = isset($profile['imce_watermark_imagecache_preset']) ? $profile['imce_watermark_imagecache_preset'] : ($common_setting ? -2 : 0);
  $form['profile']['imce_watermark_imagecache_preset'] = array(
    '#type' => 'select',
    '#title' => t('Watermark'),
    '#options' => $presets,
    '#required' => TRUE,
    '#description' => t('Set Common settings for using common watermark settings.<br/>
      Set "Watermark disabled" for turning off watermark on IMCE.<br/>
      Select "Manual script watermark" for adding watermark with custom script (warning: it\'s slow).<br/>
      Select image styles names, that have effect "Overlay (watermark)" for using imagecache_canvasactions module.'),
    '#default_value' => $selected_preset,
  );
  $form['profile']['imce_watermark_custom'] = array(
    '#type' => 'fieldset',
    '#title' => t('Manual script watermark settings'),
    '#collapsed' => $selected_preset == -2 ? FALSE : TRUE,
    '#collapsible' => TRUE,
  );
  $watermark_url = '';
  if (isset($profile['imce_watermark_custom'])) {
    $profile_custom = $profile['imce_watermark_custom'];
  }
  else {
    $profile_custom = array(
      'watermark_image' => FALSE,
      'imce_watermark_horizontal_position' => 0,
      'imce_watermark_vertical_position' => 0,
      'imce_watermark_horizontal_margin' => 0,
      'imce_watermark_vertical_margin' => 0,
      'imce_watermark_alpha' => 90,
    );
  }
  $form['previous_file'] = array(
    '#type' => 'value',
    '#value' => 0,
  );
  $fid = isset($profile_custom['watermark_image']) ? $profile_custom['watermark_image'] : FALSE;
  if ($fid) {
    $file = file_load($fid);
    if ($file) {
      $watermark_url = file_create_url($file->uri);
      $form['profile']['imce_watermark_custom']['watermark_url'] = array(
        '#type' => 'item',
        '#title' => t('Current watermark image'),
        '#markup' => theme('image', array(
          'path' => $watermark_url,
          'title' => $watermark_url,
        )),
      );
      $form['previous_file']['#value'] = $fid;
    }
  }
  $form['profile']['imce_watermark_custom']['watermark_image'] = array(
    '#name' => 'files[watermark_image]',
    '#type' => 'file',
    '#title' => t('Watermark image'),
  );
  $form['profile']['imce_watermark_custom']['imce_watermark_horizontal_position'] = array(
    '#type' => 'select',
    '#title' => t('Horizontal position of watermark'),
    '#options' => array(
      0 => t('left'),
      1 => t('middle'),
      2 => t('right'),
    ),
    '#default_value' => $profile_custom['imce_watermark_horizontal_position'],
  );
  $form['profile']['imce_watermark_custom']['imce_watermark_vertical_position'] = array(
    '#type' => 'select',
    '#title' => t('Vertical position of watermark'),
    '#options' => array(
      0 => t('top'),
      1 => t('center'),
      2 => t('bottom'),
    ),
    '#default_value' => $profile_custom['imce_watermark_vertical_position'],
  );
  $form['profile']['imce_watermark_custom']['imce_watermark_horizontal_margin'] = array(
    '#type' => 'textfield',
    '#title' => t('Horizontal margin, px'),
    '#default_value' => $profile_custom['imce_watermark_horizontal_margin'],
    '#description' => t('Set minus or plus signed value for moving watermark to left or right from defined position.'),
  );
  $form['profile']['imce_watermark_custom']['imce_watermark_vertical_margin'] = array(
    '#type' => 'textfield',
    '#title' => t('Vertical margin, px'),
    '#default_value' => $profile_custom['imce_watermark_vertical_margin'],
    '#description' => t('Set minus or plus signed value for moving watermark to higher or lower from defined position.'),
  );
  $form['profile']['imce_watermark_custom']['imce_watermark_alpha'] = array(
    '#type' => 'textfield',
    '#title' => t('Alpha level value'),
    '#default_value' => $profile_custom['imce_watermark_alpha'],
  );
  $form['#validate'][] = 'imce_watermark_settings_validate';
  $form['#submit'][] = 'imce_watermark_settings_submit';
}

/**
 * Validate watermark settings.
 */
function imce_watermark_settings_validate(&$form, &$form_state) {
  $profile =& $form_state['values']['profile'];
  if ($profile['imce_watermark_imagecache_preset'] == -2) {

    // If required, validate the uploaded picture.
    $validators = array(
      'file_validate_is_image' => array(),
    );
    $prev_fid = isset($form_state['values']['previous_file']) ? $form_state['values']['previous_file'] : 0;
    if (!empty($_FILES['files']['name']['watermark_image'])) {

      // Save the file as a temporary file.
      $file = file_save_upload('watermark_image', $validators, file_default_scheme() . '://');
      if ($file === FALSE) {
        form_set_error('watermark_image', t("Failed to upload watermark image."));
      }
      elseif ($file !== NULL) {
        $form_state['values']['watermark_uploaded_image'] = $file;
        $profile['imce_watermark_custom']['watermark_image'] = $file->fid;
        if ($file->fid != $prev_fid) {

          // clearing previous watermark file.
          $prev_file = file_load($prev_fid);
          if ($prev_file) {
            file_delete($prev_file);
          }
        }
      }
    }
    else {
      $profile['imce_watermark_custom']['watermark_image'] = $prev_fid;
    }
  }
}

/**
 * Submit watermark settings.
 */
function imce_watermark_settings_submit($form, &$form_state) {
  $common_setting = isset($form_state['imce_watermark_common_setting']) ? $form_state['imce_watermark_common_setting'] : FALSE;
  if ($common_setting) {
    variable_set('imce_watermark_setting', $form_state['values']['profile']);
  }
  else {
    $profile = $form_state['values']['profile'];
    if ($profile['imce_watermark_imagecache_preset'] == -2 && isset($form_state['values']['watermark_uploaded_image'])) {
      $form_state['values']['watermark_uploaded_image']->status = FILE_STATUS_PERMANENT;
      file_save($form_state['values']['watermark_uploaded_image']);
    }
  }
}

/*
 * Implement hook_form_FORM_ID_alter for IMCE file uploading form.
 */
function imce_watermark_form_imce_upload_form_alter(&$form, $form_state, $form_id) {
  $imce =& $form_state['build_info']['args'][0]['imce'];
  $preset = isset($imce['imce_watermark_imagecache_preset']) ? $imce['imce_watermark_imagecache_preset'] : 0;
  if (!$preset) {

    // empty or zero mean common settings.
    $imce_watermark_setting = variable_get('imce_watermark_setting');
    $preset = $imce_watermark_setting['imce_watermark_imagecache_preset'];
  }
  else {
    $imce_watermark_setting = $imce['imce_watermark_custom'];

    //    $preset = $imce_watermark_setting['imce_watermark_imagecache_preset'];
  }
  if ($preset != -1) {
    if (user_access('imce watermark control')) {
      $imce_watermark = isset($_SESSION['$imce_watermark']) ? $_SESSION['$imce_watermark'] : TRUE;
      $form['fset_upload']['upload']['#weight'] = 10;
      $form['fset_upload']['thumbnails']['#weight'] = 5;
      $form['fset_upload']['watermark'] = array(
        '#type' => 'checkbox',
        '#title' => t('Watermark'),
        '#default_value' => $imce_watermark,
        '#weight' => 1,
      );
    }
    else {
      $form['watermark'] = array(
        '#type' => 'value',
        '#value' => TRUE,
      );
    }
    $form['fset_upload']['upload']['#submit'][] = 'imce_watermark_upload_submit';
  }
}

/**
 * Add watermark at IMCE submit.
 */
function imce_watermark_upload_submit($form, &$form_state) {
  $imce =& $form_state['build_info']['args'][0]['imce'];
  $preset = isset($imce['imce_watermark_imagecache_preset']) ? $imce['imce_watermark_imagecache_preset'] : 0;
  if (!$preset) {
    $imce_watermark_setting = variable_get('imce_watermark_setting');
    $preset = $imce_watermark_setting['imce_watermark_imagecache_preset'];
    $imce_watermark_setting = $imce_watermark_setting['imce_watermark_custom'];
  }
  else {
    $imce_watermark_setting = $imce['imce_watermark_custom'];

    //    $preset = $imce_watermark_setting['imce_watermark_imagecache_preset'];
  }
  if (!$form_state['values']['watermark']) {
    return;
  }
  if ($preset == -1) {
    return;
  }
  $uploaded = array();
  if ($imce['added'][0]) {
    foreach ($imce['added'] as $added) {
      $fid = $added['id'];
      $file = file_load($fid);
      if ($file) {
        $filepath = drupal_realpath($file->uri);
      }
      if (!$filepath || !file_exists($filepath)) {
        continue;
      }
      if (count(file_validate_is_image($file)) > 0) {
        continue;
      }
      if ($preset == -2) {

        // Custom script watermarking
        $fid = $imce_watermark_setting['watermark_image'];
        if ($fid) {
          $file = file_load($fid);
          $watermark_filepath = '';
          if ($file) {
            $watermark_filepath = drupal_realpath($file->uri);
          }
        }
        if (!$watermark_filepath || !file_exists($watermark_filepath)) {
          form_set_error(NULL, t('Watermark image not exists. Please refer to site administrator...'));
          return;
        }
        $watermark = new _imce_watermark();
        $result = $watermark
          ->create_watermark($filepath, $watermark_filepath, $imce_watermark_setting);
        if (!$result) {
          form_set_error(NULL, t('Creating watermark failed'));
        }
      }
      else {

        // Watermarking by imagecache actions
        $style = image_style_load($preset);
        if (!$style) {
          form_set_error(NULL, t('Style not exists. Please refer to site administrator...'));
          return;
        }
        image_style_create_derivative($style, $filepath, $filepath);
      }
    }
  }
}

/**
 * Implements hook_form_FORMID_alter().
 * TODO Add button for watermarking on files viewing window.
 *
function imce_watermark_form_imce_fileop_form_alter(&$form, &$form_state, $form_id) {
  $imce = &$form_state['build_info']['args'][0]['imce'];
  if (imce_perm_exists($imce, 'rename')) {
    $form['fset_rename'] = array(
      '#type' => 'fieldset',
      '#title' => t('Rename'),
    ) + imce_rename_form($imce);
    array_unshift($form['#validate'], 'imce_rename_prevalidate'); // Needed to override some validation when renaming folders
    drupal_add_js(drupal_get_path('module', 'imce_rename') .'/imce_rename.js');
    drupal_add_css(drupal_get_path('module', 'imce_rename') .'/imce_rename.css');
  }
}
*/

/*
 * This class taken from: http://www.devshed.com/c/a/PHP/Dynamic-Watermarking-with-PHP/
 * with some modification.
 */
class _imce_watermark {

  /**
   * Watermarking image type
   *
   * @var string
   */
  var $image_type = "jpg";

  # given two images, return a blended watermarked image
  function create_watermark($filepath, $watermark_filepath, $watermark_setting) {
    $main_img_obj = $this
      ->create_image($filepath, TRUE);
    if (!$main_img_obj) {
      form_set_error(NULL, t('Creating image object failed, please refer to site administrator...'));
      return FALSE;
    }
    $watermark_img_obj = $this
      ->create_image($watermark_filepath);
    if (!$watermark_img_obj) {
      form_set_error(NULL, t('Creating watermark image object failed, please refer to site administrator...'));
      return FALSE;
    }
    $alpha_level = $watermark_setting['imce_watermark_alpha'] / 100;

    # convert 0-100 (%) alpha to decimal

    # calculate our images dimensions
    $main_img_obj_w = imagesx($main_img_obj);
    $main_img_obj_h = imagesy($main_img_obj);
    $watermark_img_obj_w = imagesx($watermark_img_obj);
    $watermark_img_obj_h = imagesy($watermark_img_obj);
    $vm = $watermark_setting['imce_watermark_vertical_margin'];
    $hm = $watermark_setting['imce_watermark_horizontal_margin'];
    switch ($watermark_setting['imce_watermark_horizontal_position']) {
      case 0:
        $main_img_obj_min_x = $hm;
        $main_img_obj_max_x = $watermark_img_obj_w + $hm;
        break;
      case 1:

        # determine center position coordinates
        $main_img_obj_min_x = floor($main_img_obj_w / 2 - $watermark_img_obj_w / 2) + $hm;
        $main_img_obj_max_x = ceil($main_img_obj_w / 2 + $watermark_img_obj_w / 2) + $hm;
        break;
      case 2:
        $main_img_obj_min_x = $main_img_obj_w - $watermark_img_obj_w + $hm;
        $main_img_obj_max_x = $main_img_obj_w + $hm;
        break;
    }
    switch ($watermark_setting['imce_watermark_vertical_position']) {
      case 0:
        $main_img_obj_min_y = $vm;
        $main_img_obj_max_y = $watermark_img_obj_h + $hm;
        break;
      case 1:
        $main_img_obj_min_y = floor($main_img_obj_h / 2 - $watermark_img_obj_h / 2) + $hm;
        $main_img_obj_max_y = ceil($main_img_obj_h / 2 + $watermark_img_obj_h / 2) + $hm;
        break;
      case 2:
        $main_img_obj_min_y = $main_img_obj_h - $watermark_img_obj_h + $vm;
        $main_img_obj_max_y = $main_img_obj_h + $hm;
        break;
    }

    # create new image to hold merged changes
    $return_img = imagecreatetruecolor($main_img_obj_w, $main_img_obj_h);

    # walk through main image
    for ($y = 0; $y < $main_img_obj_h; $y++) {
      for ($x = 0; $x < $main_img_obj_w; $x++) {
        $return_color = NULL;

        # determine the correct pixel location within our watermark
        $watermark_x = $x - $main_img_obj_min_x;
        $watermark_y = $y - $main_img_obj_min_y;

        # fetch color information for both of our images
        $main_rgb = imagecolorsforindex($main_img_obj, imagecolorat($main_img_obj, $x, $y));

        # if our watermark has a non-transparent value at this pixel intersection

        # and we're still within the bounds of the watermark image
        if ($watermark_x >= 0 && $watermark_x < $watermark_img_obj_w && $watermark_y >= 0 && $watermark_y < $watermark_img_obj_h) {
          $watermark_rbg = imagecolorsforindex($watermark_img_obj, imagecolorat($watermark_img_obj, $watermark_x, $watermark_y));

          # using image alpha, and user specified alpha, calculate average
          $watermark_alpha = round((127 - $watermark_rbg['alpha']) / 127, 2);
          $watermark_alpha = $watermark_alpha * $alpha_level;

          # calculate the color 'average' between the two - taking into account the specified alpha level
          $avg_red = $this
            ->_get_ave_color($main_rgb['red'], $watermark_rbg['red'], $watermark_alpha);
          $avg_green = $this
            ->_get_ave_color($main_rgb['green'], $watermark_rbg['green'], $watermark_alpha);
          $avg_blue = $this
            ->_get_ave_color($main_rgb['blue'], $watermark_rbg['blue'], $watermark_alpha);

          # calculate a color index value using the average RGB values we've determined
          $return_color = $this
            ->_get_image_color($return_img, $avg_red, $avg_green, $avg_blue);

          # if we're not dealing with an average color here, then let's just copy over the main color
        }
        else {
          $return_color = imagecolorat($main_img_obj, $x, $y);
        }

        # END if watermark

        # draw the appropriate color onto the return image
        imagesetpixel($return_img, $x, $y, $return_color);
      }

      # END for each X pixel
    }

    # END for each Y pixel

    # return the resulting, watermarked image for display

    //return $return_img;

    // Overwrite existing with current and certain file type.
    switch ($this->image_type) {
      case 'gif':
        return imagegif($return_img, $filepath);
      case 'png':
        return imagepng($return_img, $filepath);
      case 'bmp':
        return image2wbmp($return_img, $filepath);
      default:
        return imagejpeg($return_img, $filepath);
    }
    return FALSE;
  }

  # END create_watermark()

  # average two colors given an alpha
  function _get_ave_color($color_a, $color_b, $alpha_level) {
    return round($color_a * (1 - $alpha_level) + $color_b * $alpha_level);
  }

  # END _get_ave_color()

  # return closest pallette-color match for RGB values
  function _get_image_color($im, $r, $g, $b) {
    $c = imagecolorexact($im, $r, $g, $b);
    if ($c != -1) {
      return $c;
    }
    $c = imagecolorallocate($im, $r, $g, $b);
    if ($c != -1) {
      return $c;
    }
    return imagecolorclosest($im, $r, $g, $b);
  }

  /**
   * This little function allows you to create an image based on the popular image types without worrying about what it is:
   * http://www.php.net/manual/ru/function.imagecreatefromjpeg.php#110547
   * @param type $filepath
   * @return boolean
   */
  function create_image($filepath, $set_image_type = FALSE) {
    $img_type = $this->image_type;
    $type = exif_imagetype($filepath);

    // [] if you don't have exif you could use getImageSize()
    $allowedTypes = array(
      1,
      // [] gif
      2,
      // [] jpg
      3,
      // [] png
      6,
    );
    if (!in_array($type, $allowedTypes)) {
      return false;
    }
    switch ($type) {
      case 1:
        $img_type = 'gif';
        $im = imageCreateFromGif($filepath);
        break;
      case 2:
        $img_type = 'jpg';
        $im = imageCreateFromJpeg($filepath);
        break;
      case 3:
        $img_type = 'png';
        $im = imageCreateFromPng($filepath);
        break;
      case 6:
        $img_type = 'bmp';
        $im = imageCreateFromBmp($filepath);
        break;
    }
    if ($set_image_type) {
      $this->image_type = $img_type;
    }
    return $im;
  }

}

# END watermark API

Functions

Classes

Namesort descending Description
_imce_watermark