Saturday, February 12, 2011

How to set Image.Source in WPF?


I found this information to be useful for newbie, as setting up the image source from the code is not straight forward

in WPF Application. Consider following XAML
XAML::
<image Name="imgApplication" HorizontalAlignment="Center" Source="myApp.png" Margin="0,0,17,0" VerticalAlignment="Center" Stretch="None"/>

here if we want to change this "imgApplication" image with some other image from code we can use following code.


Code::
ImageSourceConverter c = new ImageSourceConverter();
imgApplication.Source = (ImageSource)c.ConvertFromString(@"C:\myNewApp.png");

Here,
@"C:\myNewApp.png" specifies the path to the new image.


By Resource Image:


In the same way if you have added the image in Resource then you can use following code:
imgApplication.Source = BitmapSourceFromImage(Properties.Resources.myNewAppPNG);

Here,
"myNewAppPNG" is the name of the image added in resource.
"BitmapSourceFromImage()" is a function to convert the image to type "ImageSource"

public BitmapSource BitmapSourceFromImage(System.Drawing.Image img)
{
      System.IO.MemoryStream memStream = new System.IO.MemoryStream();
      //save the image to memStream as a png
      img.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);

      //gets a decoder from this stream
      System.Windows.Media.Imaging.PngBitmapDecoder decoder = new
              System.Windows.Media.Imaging.PngBitmapDecoder( memStream,
              System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat,  
              System.Windows.Media.Imaging.BitmapCacheOption.Default);
        return decoder.Frames[0];
}

That's it.

No comments:

Post a Comment