Photoshop overlay blending with opacity in PHP


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. /**
  2.  * Overlay blending
  3.  *
  4.  * This function mimics Photoshop overlay blending mode by accepting two RGB arrays,
  5.  * one which will be overlayed and one which will overlay. The exact equation for overlay
  6.  * is not known, however Kevin Jensen has a pretty accurate equation available on his website.
  7.  * Please see http://www.venture-ware.com/kevin/coding/lets-learn-math-photoshop-blend-modes/
  8.  *
  9.  * @param array $bottom Color to be overlayed formatted as RGB array, i.e. for red array(255, 0, 0)
  10.  * @param array $top Color which overlays $bottom formatted as RGB array, i.e. for white array(255, 255, 255)
  11.  * @param float $opacity Optional opacity to be applied to the overlayed color in relation to $bottom
  12.  *
  13.  * @return array Color resulted in overlaying formatted as RGB array
  14.  */
  15. function blend_overlay($bottom, $top, $opacity = NULL) {
  16. // Overlay $bottom with $top
  17. $overlay = array();
  18. foreach ($bottom as $i => $a) {
  19. $b = $top[$i];
  20. if ($a < 128) {
  21. $overlay[$i] = (int) (2 * $b * $a / 255);
  22. } else {
  23. $overlay[$i] = (int) (255 * (1 - 2 * (1 - $b / 255) * (1 - $a / 255)));
  24. }
  25. }
  26.  
  27. // Apply opacity to $overlay in relation to $bottom
  28. if (isset($opacity)) {
  29. foreach ($overlay as $i => $b) {
  30. $a = $bottom[$i];
  31. $overlay[$i] = (int) ((1 - $opacity) * $a + $opacity * $b);
  32. }
  33. }
  34.  
  35. return $overlay;
  36. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.