public function opacity(&$image, $opacity)
{
if ($image->isAnimated()) {
// Ignore animated GIF for now
return $this;
}
// Bounds checks
$opacity = $opacity > 1 ? 1 : $opacity;
$opacity = $opacity < 0 ? 0 : $opacity;
for ($y = 0; $y < $image->getHeight(); $y++) {
for ($x = 0; $x < $image->getWidth(); $x++) {
$rgb = imagecolorat($image->getCore(), $x, $y);
$alpha = $rgb >> 24 & 0x7f;
// 127 in hex. These are binary operations.
$r = $rgb >> 16 & 0xff;
$g = $rgb >> 8 & 0xff;
$b = $rgb & 0xff;
// Reverse alpha values from 127-0 (transparent to opaque) to 0-127 for easy math
// Previously: 0 = opaque, 127 = transparent.
// Now: 0 = transparent, 127 = opaque
$reverse = 127 - $alpha;
$reverse = round($reverse * $opacity);
if ($alpha < 127) {
// Process non transparent pixels only
imagesetpixel($image->getCore(), $x, $y, imagecolorallocatealpha($image->getCore(), $r, $g, $b, 127 - $reverse));
}
}
}
return $this;
}