You are here

protected function GDOperationTrait::filterOpacity in Image Effects 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/ImageToolkit/Operation/gd/GDOperationTrait.php \Drupal\image_effects\Plugin\ImageToolkit\Operation\gd\GDOperationTrait::filterOpacity()
  2. 8.2 src/Plugin/ImageToolkit/Operation/gd/GDOperationTrait.php \Drupal\image_effects\Plugin\ImageToolkit\Operation\gd\GDOperationTrait::filterOpacity()

Change overall image transparency level.

This method implements the algorithm described in http://php.net/manual/en/function.imagefilter.php#82162

Parameters

resource $img: Image resource id.

int $pct: Opacity of the source image in percentage.

Return value

bool Returns TRUE on success or FALSE on failure.

See also

http://php.net/manual/en/function.imagefilter.php#82162

1 call to GDOperationTrait::filterOpacity()
Opacity::execute in src/Plugin/ImageToolkit/Operation/gd/Opacity.php
Performs the actual manipulation on the image.

File

src/Plugin/ImageToolkit/Operation/gd/GDOperationTrait.php, line 243

Class

GDOperationTrait
Trait for GD image toolkit operations.

Namespace

Drupal\image_effects\Plugin\ImageToolkit\Operation\gd

Code

protected function filterOpacity($img, $pct) {
  if (!isset($pct)) {
    return FALSE;
  }
  $pct /= 100;

  // Get image width and height.
  $w = imagesx($img);
  $h = imagesy($img);

  // Turn alpha blending off.
  imagealphablending($img, FALSE);

  // Find the most opaque pixel in the image (the one with the smallest alpha
  // value).
  $min_alpha = 127;
  for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {
      $alpha = imagecolorat($img, $x, $y) >> 24 & 0xff;
      if ($alpha < $min_alpha) {
        $min_alpha = $alpha;
      }
    }
  }

  // Loop through image pixels and modify alpha for each.
  for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {

      // Get current alpha value (represents the TANSPARENCY!).
      $color_xy = imagecolorat($img, $x, $y);
      $alpha = $color_xy >> 24 & 0xff;

      // Calculate new alpha.
      if ($min_alpha !== 127) {
        $alpha = 127 + 127 * $pct * ($alpha - 127) / (127 - $min_alpha);
      }
      else {
        $alpha += 127 * $pct;
      }

      // Get the color index with new alpha.
      $alpha_color_xy = imagecolorallocatealpha($img, $color_xy >> 16 & 0xff, $color_xy >> 8 & 0xff, $color_xy & 0xff, $alpha);

      // Set pixel with the new color + opacity.
      if (!imagesetpixel($img, $x, $y, $alpha_color_xy)) {
        return FALSE;
      }
    }
  }
  return TRUE;
}