Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply feBlend and preserve source alpha

I'm trying to modify colors of an image by applying feFlood and feBlend to it in "lighten" and "darken" modes. How do I preserve the alpha channel?

<svg>
  <filter id="filter">
    <feFlood result="flood" flood-color="blue" />
    <feBlend in="SourceGraphic" in2="flood" mode="lighten" />
  </filter>
  <image filter="url(#filter)" href="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
</svg>

https://jsfiddle.net/utqghr0o/

like image 276
Alexander Shutau Avatar asked Dec 09 '25 06:12

Alexander Shutau


1 Answers

The way lighten works is that it takes the maximum colour value from each channel of each of the two inputs (pre-multiplied with the alpha). So if a pixel has zero opacity, it will not ever count as the maximum colour for any channel, and the value from the other input will be used.

What you need to do is first mask the flood with the alpha from the source image ("SourceAlpha"), then blend the masked flood with the original image.

<svg width="544" height="184">
  <filter id="filter">
    <feFlood result="flood" flood-color="blue" />
    <feComposite in="flood" in2="SourceAlpha" operator="atop" result="maskedflood"/>
    <feBlend in="SourceGraphic" in2="maskedflood" mode="lighten" />
  </filter>
  <image filter="url(#filter)" width="544" height="184" href="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
</svg>
like image 125
Paul LeBeau Avatar answered Dec 11 '25 19:12

Paul LeBeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!