Fastest image merge (alpha blend) in GDI+ #code#gdi#matrix Compares the performance of GetPixe l/ SetPixel, ColorMatrix, and raw image data access for merging images in GDI+ (C# / System.Drawing APIs)
Updated on Friday, December 9, 2022
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.
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.
Newsletter
Related
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 tools....
Scanning from the ADF using WIA in C# — I've been going nuts trying to scan from the document feeder on my Canon imageClass MF4150. Everything worked as expected from the flatbed, no dice trying to persuade the ADF to kick in. I found some sample code but it was oriented towards...
Merging Resource Dictionaries for fun and profit — Here are two scenarios where merged ResourceDictionary objects are the way forward. I’m working on a WPF project that needs to be single instance. Heaven forbid that the WPF team should pollute the purity of their framework with support for...
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.