Return to Snippet

Revision: 63055
at April 4, 2013 21:48 by laurikar


Initial Code
/**
 * Overlay blending
 *
 * This function mimics Photoshop overlay blending mode by accepting two RGB arrays,
 * one which will be overlayed and one which will overlay. The exact equation for overlay
 * is not known, however Kevin Jensen has a pretty accurate equation available on his website.
 * Please see http://www.venture-ware.com/kevin/coding/lets-learn-math-photoshop-blend-modes/
 *
 * @param array $bottom Color to be overlayed formatted as RGB array, i.e. for red array(255, 0, 0)
 * @param array $top Color which overlays $bottom formatted as RGB array, i.e. for white array(255, 255, 255)
 * @param float $opacity Optional opacity to be applied to the overlayed color in relation to $bottom
 *
 * @return array Color resulted in overlaying formatted as RGB array
 */
function blend_overlay($bottom, $top, $opacity = NULL) {
	// Overlay $bottom with $top
	$overlay = array();
	foreach ($bottom as $i => $a) {
		$b = $top[$i];
		if ($a < 128) {
			$overlay[$i] = (int) (2 * $b * $a / 255);
		} else {
			$overlay[$i] = (int) (255 * (1 - 2 * (1 - $b / 255) * (1 - $a / 255)));
		}
	}

	// Apply opacity to $overlay in relation to $bottom
	if (isset($opacity)) {
		foreach ($overlay as $i => $b) {
			$a = $bottom[$i];
			$overlay[$i] = (int) ((1 - $opacity) * $a + $opacity * $b);
		}
	}

	return $overlay;
}

Initial URL


Initial Description
This function mimics Photoshop overlay blending by accepting two RGB arrays, one which will be overlayed and one which will overlay. Opacity is optional.

Initial Title
Photoshop overlay blending with opacity in PHP

Initial Tags
php, color

Initial Language
PHP