[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/sites/all/modules/imageapi/ -> imageapi_gd.module (source)

   1  <?php // $Id$
   2  
   3  /**
   4   * @file
   5   * GD2 toolkit functions
   6   */
   7  
   8  /**
   9   * Implementation of hook_imageapi_toolkit().
  10   *
  11   * this hook only gets called to see is a module implements the imageapi hooks...
  12   */
  13  function imageapi_gd_imageapi_toolkit() {
  14  }
  15  
  16  
  17  /**
  18   * Settings form for the toolkit.
  19   */
  20  function imageapi_gd_settings_form() {
  21    $form['imageapi_jpeg_quality'] = array(
  22      '#type' => 'textfield',
  23      '#title' => t('JPEG quality'),
  24      '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality, but bigger files.'),
  25      '#size' => 10,
  26      '#maxlength' => 3,
  27      '#default_value' => variable_get('imageapi_jpeg_quality', 75),
  28      '#field_suffix' => '%',
  29    );
  30    $form['imageapi_crop_background'] = array(
  31      '#type' => 'textfield',
  32      '#title' => t('Crop background'),
  33      '#description' => t('Hex string specifying the background color to use when cropping images. If not provided, will use the default. Examples: "ABC", "ABCD", "AABBCC", "AABBCCDD".'),
  34      '#size' => 10,
  35      '#maxlength' => 8,
  36      '#default_value' => variable_get('imageapi_crop_background', ''),
  37      '#field_prefix' => '#',
  38    );
  39    $form['imageapi_interlaced'] = array(
  40      '#title' => t('Enable Interlacing'),
  41      '#type' => 'checkbox',
  42      '#default_value' => variable_get('imageapi_interlaced', 0),
  43      '#description' => t('Interlacing is a method of encoding a bitmap image such that a person who has partially received it sees a degraded copy of the entire image. When communicating over a slow communications link, this is often preferable to seeing a perfectly clear copy of one part of the image, as it helps the viewer decide more quickly whether to abort or continue the transmission.')
  44    );
  45    return system_settings_form($form);
  46  }
  47  
  48  /**
  49   * Open an image file.
  50   *
  51   * @param $image
  52   *   An image object. The $image->resource value will populated by this call.
  53   * @return
  54   *   TRUE or FALSE, based on success.
  55   */
  56  function imageapi_gd_image_open($image) {
  57    $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  58    $function = 'imagecreatefrom'. $extension;
  59    return (function_exists($function) && $image->resource = $function($image->source));
  60  }
  61  
  62  /**
  63   * Save an image file to a destination.
  64   *
  65   * @param $image
  66   *   An image object.
  67   * @param $destination
  68   *   A string file path where the image should be saved.
  69   * @param $extension
  70   *   A string containing one of the following extensions: gif, jpg, jpeg, png.
  71   * @return
  72   *   TRUE or FALSE, based on success.
  73   */
  74  function imageapi_gd_image_close($image, $destination) {
  75    $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  76    $function = 'image'. $extension;
  77    if (!function_exists($function)) {
  78      return FALSE;
  79    }
  80    if (variable_get('imageapi_interlaced', 0)) {
  81      imageinterlace($image->resource, 1);
  82    }
  83    if ($extension == 'jpeg') {
  84      return $function($image->resource, $destination, variable_get('imageapi_jpeg_quality', 75));
  85    }
  86    else {
  87      // Always save PNG images with full transparency.
  88      if ($extension == 'png') {
  89        imagealphablending($image->resource, FALSE);
  90        imagesavealpha($image->resource, TRUE);
  91      }
  92      return $function($image->resource, $destination);
  93    }
  94  }
  95  
  96  /**
  97   * Crop an image using the GD toolkit.
  98   *
  99   * @param $image
 100   *   An image object. The $image->resource, $image->info['width'], and
 101   *   $image->info['height'] values will be modified by this call.
 102   * @param $x
 103   *   The starting x offset at which to start the crop, in pixels.
 104   * @param $y
 105   *   The starting y offset at which to start the crop, in pixels.
 106   * @param $width
 107   *   The width of the cropped area, in pixels.
 108   * @param $height
 109   *   The height of the cropped area, in pixels.
 110   * @return
 111   *   TRUE or FALSE, based on success.
 112   */
 113  function imageapi_gd_image_crop(&$image, $x, $y, $width, $height) {
 114    // Create an image with the new width and height.
 115    $res = imageapi_gd_create_tmp($image, $width, $height);
 116  
 117    // Fill the background color if desired.
 118    $background = variable_get('imageapi_crop_background', '');
 119    if (!empty($background)) {
 120      $background = imageapi_hex2rgba($background);
 121      $background = imagecolorallocatealpha($res, $background[0], $background[1], $background[2], $background[3]);
 122      imagefill($res, 0, 0, $background);
 123    }
 124  
 125    // Copy the source image to our new destination image. We use
 126    // $image->info['width] instead of $width because we are copying
 127    // using the source image's width and height, not the destination
 128    // width and height.
 129    if (!imagecopyresampled($res, $image->resource, -$x, -$y, 0, 0, $image->info['width'], $image->info['height'], $image->info['width'], $image->info['height'])) {
 130      return FALSE;
 131    }
 132  
 133    // Destroy the original image and return the modified image.
 134    imagedestroy($image->resource);
 135    $image->resource = $res;
 136    $image->info['width'] = $width;
 137    $image->info['height'] = $height;
 138    return TRUE;
 139  }
 140  
 141  /**
 142   * Scale an image to the specified size using GD.
 143   *
 144   * @param $image
 145   *   An image object. The $image->resource, $image->info['width'], and
 146   *   $image->info['height'] values will be modified by this call.
 147   * @param $width
 148   *   The new width of the resized image, in pixels.
 149   * @param $height
 150   *   The new height of the resized image, in pixels.
 151   * @return
 152   *   TRUE or FALSE, based on success.
 153   */
 154  function imageapi_gd_image_resize(&$image, $width, $height) {
 155    $res = imageapi_gd_create_tmp($image, $width, $height);
 156  
 157    if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) {
 158      return FALSE;
 159    }
 160  
 161    imagedestroy($image->resource);
 162    // Update image object.
 163    $image->resource = $res;
 164    $image->info['width'] = $width;
 165    $image->info['height'] = $height;
 166    return TRUE;
 167  }
 168  
 169  /**
 170   * Rotate an image the given number of degrees.
 171   *
 172   * @param $image
 173   *   An image object. The $image->resource, $image->info['width'], and
 174   *   $image->info['height'] values will be modified by this call.
 175   * @param $degrees
 176   *   The number of (clockwise) degrees to rotate the image.
 177   * @param $background
 178   *   An hexadecimal integer specifying the background color to use for the
 179   *   uncovered area of the image after the rotation. E.g. 0x000000 for black,
 180   *   0xff00ff for magenta, and 0xffffff for white. For images that support
 181   *   transparency, this will default to transparent. Otherwise it will
 182   *   be white.
 183   * @return
 184   *   TRUE or FALSE, based on success.
 185   */
 186   function imageapi_gd_image_rotate(&$image, $degrees, $background) {
 187    // PHP installations using non-bundled GD do not have imagerotate.
 188    if (!function_exists('imagerotate')) {
 189      require_once drupal_get_path('module', 'imageapi_gd') .'/imagerotate.inc';
 190    }
 191  
 192    $width = $image->info['width'];
 193    $height = $image->info['height'];
 194  
 195    // Convert the hexadecimal background value to a color index value.
 196    if (isset($background)) {
 197      $rgb = array();
 198      for ($i = 16; $i >= 0; $i -= 8) {
 199        $rgb[] = (($background >> $i) & 0xFF);
 200      }
 201      $background = imagecolorallocatealpha($image->resource, $rgb[0], $rgb[1], $rgb[2], 0);
 202    }
 203    // Set the background color as transparent if $background is NULL.
 204    else {
 205      // Get the current transparent color.
 206      $background = imagecolortransparent($image->resource);
 207  
 208      // If no transparent colors, use white.
 209      if ($background == 0) {
 210        $background = imagecolorallocatealpha($image->resource, 255, 255, 255, 0);
 211      }
 212    }
 213  
 214    // Images are assigned a new color pallete when rotating, removing any
 215    // transparency flags. For GIF images, keep a record of the transparent color.
 216    if ($image->info['extension'] == 'gif') {
 217      $transparent_index = imagecolortransparent($image->resource);
 218      if ($transparent_index != 0) {
 219        $transparent_gif_color = imagecolorsforindex($image->resource, $transparent_index);
 220      }
 221    }
 222  
 223    $image->resource = imagerotate($image->resource, 360 - $degrees, $background);
 224  
 225    // GIFs need to reassign the transparent color after performing the rotate.
 226    if (isset($transparent_gif_color)) {
 227      $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']);
 228      imagecolortransparent($image->resource, $background);
 229    }
 230  
 231    $image->info['width'] = imagesx($image->resource);
 232    $image->info['height'] = imagesy($image->resource);
 233    return TRUE;
 234  }
 235  
 236  function imageapi_gd_image_sharpen(&$image, $radius, $sigma, $amount, $threshold) {
 237    $threshold = round($threshold * 255);
 238    $image->resource = imageapi_gd_unsharp_mask($image->resource, $radius, $sigma, $amount, $threshold);
 239    return TRUE;
 240  }
 241  
 242  /**
 243   * Convert an image resource to grayscale.
 244   *
 245   * Note that transparent GIFs loose transparency when desaturated.
 246   *
 247   * @param $image
 248   *   An image object. The $image->resource value will be modified by this call.
 249   * @return
 250   *   TRUE or FALSE, based on success.
 251   */
 252  function imageapi_gd_image_desaturate(&$image) {
 253    // PHP installations using non-bundled GD do not have imagefilter.
 254    if (!function_exists('imagefilter')) {
 255      require_once drupal_get_path('module', 'imageapi_gd') .'/imagefilter.inc';
 256    }
 257  
 258    return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
 259  }
 260  
 261  /**
 262   * Create a truecolor image preserving transparency from a provided image.
 263   *
 264   * @param $image
 265   *   An image object.
 266   * @param $width
 267   *   The new width of the new image, in pixels.
 268   * @param $height
 269   *   The new height of the new image, in pixels.
 270   * @return
 271   *   A GD image handle.
 272   */
 273  function imageapi_gd_create_tmp($image, $width, $height) {
 274    $res = imagecreatetruecolor($width, $height);
 275  
 276    if ($image->info['extension'] == 'gif') {
 277      // Grab transparent color index from image resource.
 278      $transparent = imagecolortransparent($image->resource);
 279  
 280      if ($transparent >= 0 && $transparent < imagecolorstotal($image->resource)) {
 281        // The original must have a transparent color, allocate to the new image.
 282        $transparent_color = imagecolorsforindex($image->resource, $transparent);
 283        $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
 284  
 285        // Flood with our new transparent color.
 286        imagefill($res, 0, 0, $transparent);
 287        imagecolortransparent($res, $transparent);
 288      }
 289    }
 290    elseif ($image->info['extension'] == 'png') {
 291      imagealphablending($res, FALSE);
 292      $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
 293      imagefill($res, 0, 0, $transparency);
 294      imagealphablending($res, TRUE);
 295      imagesavealpha($res, TRUE);
 296    }
 297    else {
 298      imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
 299    }
 300  
 301    return $res;
 302  }
 303  
 304  /**
 305   * $sigma is currently unused for _gd_sharp_mask due to 3x3 convolution matrix limit.
 306   * we should explore properly implementing sigma.
 307   */
 308  function imageapi_gd_unsharp_mask($img, $radius, $sigma, $amount, $threshold)    {
 309  
 310    //////////////////////////////////////////////////////////////
 311    ////
 312    ////                  Unsharp Mask for PHP - version 2.1.1
 313    ////
 314    ////    Unsharp mask algorithm by Torstein H�nsi 2003-07.
 315    ////             thoensi_at_netcom_dot_no.
 316    ////               Please leave this notice.
 317    ////
 318    //////////////////////////////////////////////////////////////
 319  
 320    // http://vikjavev.no/computing/ump.php
 321  
 322    // $img is an image that is already created within php using
 323    // imgcreatetruecolor. No url! $img must be a truecolor image.
 324  
 325    // Attempt to calibrate the parameters to Photoshop:
 326    if ($amount > 500) $amount = 500;
 327    $amount = $amount * 0.016;
 328    if ($radius > 50) $radius = 50;
 329    $radius = $radius * 2;
 330    if ($threshold > 255) $threshold = 255;
 331  
 332    $radius = abs(round($radius)); // Only integers make sense.
 333    if ($radius == 0) {
 334      return $img; imagedestroy($img);
 335      break;
 336    }
 337  
 338    $w = imagesx($img); $h = imagesy($img);
 339    $img_canvas = imagecreatetruecolor($w, $h);
 340    $img_blur = imagecreatetruecolor($w, $h);
 341  
 342    // Gaussian blur matrix:
 343    //
 344    //    1    2    1
 345    //    2    4    2
 346    //    1    2    1
 347    //
 348    //////////////////////////////////////////////////
 349  
 350    $matrix = array(
 351      array( 1, 2, 1 ),
 352      array( 2, 4, 2 ),
 353      array( 1, 2, 1 )
 354      );
 355  
 356    imagecopy($img_blur, $img, 0, 0, 0, 0, $w, $h);
 357    imageconvolution($img_blur, $matrix, 16, 0);
 358  
 359    if ($threshold > 0) {
 360      // Calculate the difference between the blurred pixels and the original
 361      // and set the pixels
 362      for ($x = 0; $x < $w-1; $x++)    { // each row
 363        for ($y = 0; $y < $h; $y++)    { // each pixel
 364  
 365          $rgb_orig = imagecolorat($img, $x, $y);
 366          $r_orig = (($rgb_orig >> 16) & 0xFF);
 367          $g_orig = (($rgb_orig >> 8) & 0xFF);
 368          $b_orig = ($rgb_orig & 0xFF);
 369  
 370          $rgb_blur = imagecolorat($img_blur, $x, $y);
 371  
 372          $r_blur = (($rgb_blur >> 16) & 0xFF);
 373          $g_blur = (($rgb_blur >> 8) & 0xFF);
 374          $b_blur = ($rgb_blur & 0xFF);
 375  
 376          // When the masked pixels differ less from the original
 377          // than the threshold specifies, they are set to their original value.
 378          $r_new = (abs($r_orig - $r_blur) >= $threshold)
 379            ? max(0, min(255, ($amount * ($r_orig - $r_blur)) + $r_orig))
 380            : $r_orig;
 381          $g_new = (abs($g_orig - $g_blur) >= $threshold)
 382            ? max(0, min(255, ($amount * ($g_orig - $g_blur)) + $g_orig))
 383            : $g_orig;
 384          $b_new = (abs($b_orig - $b_blur) >= $threshold)
 385            ? max(0, min(255, ($amount * ($b_orig - $b_blur)) + $b_orig))
 386            : $b_orig;
 387  
 388          if (($r_orig != $r_new) || ($g_orig != $g_new) || ($b_orig != $b_new)) {
 389            $pix_col = imagecolorallocate($img, $r_new, $g_new, $b_new);
 390            imagesetpixel($img, $x, $y, $pix_col);
 391          }
 392        }
 393      }
 394    }
 395    else{
 396      for ($x = 0; $x < $w; $x++)    { // each row
 397        for ($y = 0; $y < $h; $y++)    { // each pixel
 398          $rgb_orig = imagecolorat($img, $x, $y);
 399          $r_orig = (($rgb_orig >> 16) & 0xFF);
 400          $g_orig = (($rgb_orig >> 8) & 0xFF);
 401          $b_orig = ($rgb_orig & 0xFF);
 402  
 403          $rgb_blur = imagecolorat($img_blur, $x, $y);
 404  
 405          $r_blur = (($rgb_blur >> 16) & 0xFF);
 406          $g_blur = (($rgb_blur >> 8) & 0xFF);
 407          $b_blur = ($rgb_blur & 0xFF);
 408  
 409          $r_new = ($amount * ($r_orig - $r_blur)) + $r_orig;
 410          if ($r_new>255) $r_new=255;
 411          elseif ($r_new<0) $r_new=0;
 412  
 413          $g_new = ($amount * ($g_orig - $g_blur)) + $g_orig;
 414          if ($g_new>255) $g_new=255;
 415          elseif ($g_new<0) $g_new=0;
 416  
 417          $b_new = ($amount * ($b_orig - $b_blur)) + $b_orig;
 418          if ($b_new>255) $b_new=255;
 419          elseif ($b_new<0) $b_new=0;
 420  
 421          $rgb_new = ($r_new << 16) + ($g_new <<8) + $b_new;
 422          imagesetpixel($img, $x, $y, $rgb_new);
 423        }
 424      }
 425    }
 426    imagedestroy($img_canvas);
 427    imagedestroy($img_blur);
 428  
 429    return $img;
 430  }


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7