PNG optimization for smaller XAP.

May 12, 2009 at 5:26 PM

Hi everyone,

It's always important to keep XAP as small as possible. I have two ideas how to reduce the XAP size for Silverlight by PNG optimization.

1. Do 'Save for Web & Devices' when you save a png file on Photoshop.
It'll reduce your png file size dramatically. You can do it by choosing File > Save for Web & Devices on Photoshop menu or press Ctrl+Alt+Shift+S keys, and then choose PNG-24(or PNG-8) type.

2. Create a noise.png dynamically.
Look at noise.png, it's really simple and meanless 'noise' but over 700kb! So why don't we create it in dynamic code?
Fortunately, Silverlight 3 supports WriteableBitmap and APIs for do it. Also cloud.png and sincostan.png could be created by code.

Here's an example:

Random rand = new Random();

WriteableBitmap wb = new WriteableBitmap(512, 512, PixelFormats.Bgr32);

for (int x = 0; x < 512; x++)
    for (int y = 0; y < 512; y++)
        // generate a color in Pbgra32 format!
        byte[] components = new byte[4];
        components[0] = (byte)(rand.Next(255)); // b
        components[1] = (byte)(rand.Next(255)); // g
        components[2] = (byte)(rand.Next(255)); // r
        components[3] = 0;      // unused

        // you could certainly do your own masking here
        int pixelValue = BitConverter.ToInt32(components, 0);

        // set the pixel value
        wb[y * 512 + x] = pixelValue;

Hope XAP size will be reduced for next release. :D