WPF Image Dynamically changing Image source during runtime

John Batdorf picture John Batdorf · Dec 29, 2008 · Viewed 122.7k times · Source

I have a window with a title on it. When the user selects a choice from a drop down list, the title image can change. The problem is when the image loads, it's a blurred, stretched, and pixelated. These are PNG files I'm working with and they look good prior to setting the source dynamically.

Here's the code I'm using to change the image's source.

string strUri2 = String.Format(@"pack://application:,,,/MyAssembly;component/resources/main titles/{0}", CurrenSelection.TitleImage);
Stream iconStream2 = App.GetResourceStream(new Uri(strUri2)).Stream;
imgTitle.Source = HelperFunctions.returnImage(iconStream2);

Here are the helper functions.

    public static BitmapImage returnImage(Stream iconStream)
    {
        Bitmap brush = new Bitmap(iconStream);
        System.Drawing.Image img = brush.GetThumbnailImage(brush.Height, brush.Width, null, System.IntPtr.Zero);
        var imgbrush = new BitmapImage();
        imgbrush.BeginInit();
        imgbrush.StreamSource = ConvertImageToMemoryStream(img);
        imgbrush.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        imgbrush.EndInit();
        var ib = new ImageBrush(imgbrush);
        return imgbrush;
    }

    public static MemoryStream ConvertImageToMemoryStream(System.Drawing.Image img)
    {
        var ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms;
    }

And the XAML

            <Image x:Name="imgTitle" HorizontalAlignment="Left" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" Stretch="None" d:IsLocked="False"/>

And for Ref:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

Anyone have any ideas what's up?

Answer

Nir picture Nir · Dec 29, 2008

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx