« Back to blog

Dynamically Adding Images in a UI

Now i am sure that there are many ways of doing this but i found a quick and easy method of this for a silverlight UI with a C# code behind. All you need is the File (which is a jpg/png) on your harddisk. So here it is: creating Image from byte[] / file #region Image from FileInfo Image myImage = new Image(); //the image can be a xaml object also FileInfo file = new FileInfo(""); //available from a file browser window BitmapImage bitmapImage = new BitmapImage(); using (Stream stream = file.OpenRead()) { bitmapImage.SetSource(stream); } myImage.Source = bitmapImage; #endregion #region Image from byte[] Image myImage = new Image(); //the image can be a xaml object also byte[] data = null;//provided by service or anyother data source BitmapImage bitmapImage = new BitmapImage(); using (Stream stream = new MemoryStream(data)) { bitmapImage.SetSource(stream); } myImage.Source = bitmapImage; #endregion Here myImage in both the codes is nothing but a UI element being shown on the Screen. You can set its layout and size attributes as you wish and set. In essence you are creating an image in memory using a BitmapImage object and then setting it as the source of the Image object. What is important to note is that Silverlight only recognizes .jpg or .png files. Surprisingly it does not support .gif files. So there you are. A simple, quick and effortless way of showing thumbnails or pictures dynamically in your Silverlight UI. This is what i used, when i was creating an upload utility for an application. Hope this helps. :)