I've been experimenting with the best way to merge two images in C#. That is, paint one image on top of another with some level of transparency as opposed to using one color as a transparency mask. I tried three candidates, all included below:
SimpleBlend is the naive approach using GetPixel and SetPixel to add the desired alpha value to the second image before painting it on top of the first.
MatrixBlend configures a ColorMatrix to specify the desired alpha and then paints the second image on to the first using the matrix.
ManualBlend locks and directly manipulates the image data. This uses pointers and so introduces unsafe code (it's possible to marshal the image data into a managed array but I wanted to look at the performance with raw access).
I tested each approach ten times with a couple of large JPEG images. The results are:
I expect ManualBlend could be optimized further but both this and MatrixBlend are an order of magnitude faster than the naive approach. I'll be using MatrixBlend as no unsafe code is required.
Both images might already contain alpha channels and these three blending functions are not equivalent in this case.
The `ManualBlend` has the greatest potential to merge alphas correctly --- just one more `finAlpha = (uint)((alphaSrc * (float)srcAlpha) + (alphaDst * (float)dstAlpha))`
Unfortunately it seems impossible to produces such merged alpha channel with `MatrixBlend` though which is very unfortunate.
Add Comment
All comments are moderated. Your email address is used to display a Gravatar
and optionally for notification of new comments and to sign up for the newsletter.
Improving the accuracy of the new Catfood Earth clouds layer — Last weekend I rushed out a new version of Catfood Earth because the clouds layer stopped working. I'd been using xplanet clouds which published a free 2048x1024 image infrequently and for some reason the site has vanished...
Style Transfer for Time Lapse Photography — TensorFlow Hub has a great sample for transferring the style of one image to another. You might have seen Munch's The Scream applied to a turtle, or Hokusai's The Great Wave off Kanagawa to the Golden Gate Bridge. It's...
Crushing PNGs in .NET — I'm working on page speed and Google PageSpeed Insights is telling me that my PNGs are just way too large. Sadly .NET does not provide any way to optimize PNG images so there is no easy fix - just unmanaged libraries and command line...
Add Comment
All comments are moderated. Your email address is used to display a Gravatar and optionally for notification of new comments and to sign up for the newsletter.