Freigeben über


Optimized Joe Stegman's Dynamic Image Generation (Twice the Speed)

I needed a good and relatively fast dynamic image generation code for Silverlight (for the next sample, you’ll see).

Joe Stegman has an excellent post including source code for generating images in Silverlight: https://blogs.msdn.com/jstegman/archive/2008/04/21/dynamic-image-generation-in-silverlight.aspx

Joe’s code is simple and easy to understand, but can be optimized for speed quite a bit.

After doing some profiling (looking in Task Manager) and optimizations, I managed to speed up the code more than twice. To find out the slowest functions, I just ran and image generation in a loop and looked at the CPU usage in Task Manager when disabling each of the functions.

These are the things I updated:

· All the image data is not copied anymore in the WriteChunk() function

· One big array was initialized on every frame in Encode()

· Changed SetPixel() to remove some checks in Release mode

· The Adler32 algorithm was amazingly slow (it’s doing two prime number divisions for each pixel)…after looking at Wikipedia I found a trick that makes the adler use 5550 times less divisions J

The optimized source is here: https://blogs.msdn.com/nikola/attachment/8690157.ashx

Further optimizations

There can be more optimizations, for example the PngEncoder always works with the same image width/height, so it may avoid some calls to write to a memory stream and bulk several calls into one.

The second memory stream in Encode() can be removed.

Maybe the image can be stored png-encoded and just updated by SetPixel. This way the stream creation will be very fast. This will be good if for example only 10% of the pixels are changed each frame.

I hope someone else will pick up the source finish what we started J (or I’ll finish it later)

Note: this is a remake of a post that was accidentally deleted.

EditableImage.zip