Fastest image merge (alpha blend) in GDI+

Updated on Friday, December 9, 2022

Blended image from Catfood Earth

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:

SimpleBlend: 17.69 seconds
MatrixBlend: 0.74 seconds
ManualBlend: 1.13 seconds

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.

Add your comment...

Related Posts

You Might Also Like

(All Code Posts)


richad lee

MatrixBlend() works like a charm, this saved my day


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.



Crushing PNGs in .NET