Dynamic Image Generation in Silverlight


 


I’ve posted a sample PNG image generator here (Beta 1 bits). 


 


This has 3 dynamically generated images – one randomly filled 64×64 image that’s updated at 6 frames/sec.  A second 128×128 image with a gradient fill and a third that’s a 512×512 dynamically generated image of the Mandelbrot set.  When running the page you’ll see performance is quite good (each page refresh will re-create all images).  Note that there are still some optimizations that can be made to minimize re-writes of bytes and if anyone updates this, let me know and I’ll post the updated sample.


 


You can find the source here.  It’s fairly small as I don’t generate a compressed image and therefore don’t need the PNG compression library (ZLIB).  On the flip side, the dynamically generated image is not well suited for local storage since its not compressed.


 


The API to dynamically generate an image and assign it to an Image element is fairly straight-forward:


 


      ei = new EditableImage(height, width);      // EditableImage class from this sample


      image = new BitmapImage();


 


      // Generate gradient filled image


      for (int idx = 0; idx < height; idx++)      // Height (y)


      {


        for (int jdx = 0; jdx < width; jdx++)     // Width (x)


        {


          ei.SetPixel(jdx, idx, (byte)idx, (byte)jdx, 255, 255);


        }


      }


 


      // Get stream and set image source


      image.SetSource(ei.GetStream());


      img2.Source = image;                  // img2 is an Image element


 


 


Image sample


Comments (24)

  1. Apr&#232;s un premier billet dans la rubrique &quot;Cookbook Silverlight&quot; qui parlait d’un contr&#244;le

  2. rob_houweling says:

    Hi Joe,

    Great stuff!!

    I was wondering though… Is it possible to read the stream of an image using your EditableImage class? Or is this a limitation of SL2 beta 1?

    If it was possible, it would create opportunities for image editing/effects.

    Kind regards,

    Rob Houweling

  3. Joe Stegman has been hard at work making this happen and has now released an initial version of his PNG

  4. I’ve been OOF on vacation (Hawaii, where it’s warm!).&#160; But I’m back now and here’s a few new sample

  5. planetmarshalluk says:

    Funnily enough I was looking at doing this the other day, you just saved me a lot of work. I’ve made a couple of modifications, which you may want to consider

    * PNGEncoder

     * Adler32 algorithm. There are some optimizations you could make here, see the Wikipedia article for details on a C implementation which is straightforward to convert to C#

     * Use Array.Copy instead of manual array copies – this is significntly faster

    * EditableBitmap

     * provide a delegate interface implementing the Visitor pattern as well as SetPixel, or something like WPF’s WriteableBitmap.WritePixels(). Writing all the pixels in a single op is significantly faster than repeatedly calling SetPixel()

    It should be noted however that writing the pixels is really your bottleneck, so optimizing the Encoder won’t make much of a difference.

    I’m currently playing with some multithreaded approaches and will let you know what I come up with.

    Thanks again,

    Andrew.

  6. planetmarshalluk says:

    You need to take a look at the for loop in PngEncoder.Encode(). The number of iterations in the loop ( ie the number of blocks written ) is equal to pixelwidth/rowsperblock, which is not what you want ( try creating an image 400×300 and you’ll see what I mean ).

    I would replace the for loop with something like this,

         uint nblocks = dcSize / _MAXBLOCK;

         uint nbytes = nblocks * _MAXBLOCK;

         for ( int offset = 0; offset < nbytes; offset += _MAXBLOCK )

         {

             comp.WriteByte(0x00);

             // write LEN ( length of block )

           comp.Write(BitConverter.GetBytes(_MAXBLOCK), 0, 2);

           // Write one’s compliment of LEN

           comp.Write(BitConverter.GetBytes(0), 0, 2);

           // Write block

           comp.Write(data, offset, _MAXBLOCK);

         }

           // write last block

             comp.WriteByte(0x01);

             // write LEN ( length of block )

         uint lastBlock = dcSize – nbytes;

           comp.Write(BitConverter.GetBytes(lastBlock), 0, 2);

           // Write one’s compliment of LEN

           comp.Write(BitConverter.GetBytes((ushort) ~lastBlock), 0, 2);

           // Write block

           comp.Write(data, (int) nbytes, (int)lastBlock);

  7. planetmarshalluk says:

    whoops – need to modify that last bit of code to deal with images that are an exact multiple of MAXBLOCK bytes. The code will still work, but the last block is of zero length in those cases.

    D’oh!

  8. mdonatas says:

    You’ve done an incredible job! Since PNG encoder was a bit over my head, custom BMP encoder had to suffice. Superb… simply superb! Thanks a bunch 🙂

    On the other hand this comming from you probably means that Silverlight 2.0 final won’t have native support for System.Drawing

  9. I fixed a few bugs in the ImageGenerator sample . One was related to non-square images and the other

  10. ismail codar says:

    If you setting up height = 500 and width = 500 or greather then in  dt_Tick method test screen is can’t dislaying.

    Especially performance is problem for animations. I hope next silverlight version is native support raster drawing.

  11. LarsG says:

    Thx this inspired me to try to do some animations with it.. doing some old school 2d water ripples..

    Lars

  12. One of the things that I’ve been meaning to experiment with around the MultiScaleImage control in Silverlight…

  13. I needed a good and relatively fast dynamic image generation code for Silverlight (for the next sample,

  14. In this tutorial: – creating and rendering water ripples – optimized image generation – JPEG decoding

  15. I needed a good and relatively fast dynamic image generation code for Silverlight (for the next sample,

  16. In this tutorial: – creating and rendering water ripples – optimized image generation – JPEG decoding

  17. So I&#39;ve just finished version 1.0 of my Silverlight spectrum emulator. At the moment there is no

  18. Minh T. Nguyen ‘s Mandelbrot Explorer is an application that allows you to zoom into the Mandelbrot set

  19. Paint applications on the desktop has been developing for a long time however there are few available

  20. "Software" rendering in Balder

  21. Luis J Acedo says:

    When I click to see the Beta 1, it launch older silverlight install version. and the site does not run. You may need to check your deploy site to allow other version of silverlight to work with your site.

    Thanks

    Luis J Acedo

  22. pablo says:

    I need 50% more compressed the image, which should change in the code

    thanks

  23. gareth says:

    thanks for this great – but a question:

    why is the Width Property in the EditableImage class limited to a max of 2048?