[wpf] WPF Image Dynamically changing Image source during runtime

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?

This question is related to wpf image dynamic execution

The answer is


Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

Me.imgAddNew.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/SPMS;component/Images/Cancel__Red-64.png", UriKind.Relative))

Here is how it worked beautifully for me. In the window resources add the image.

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

Then the code goes like this.

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

"this" is referring to the Window object


Try Stretch="UniformToFill" on the Image


Me.imgAddNew.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/SPMS;component/Images/Cancel__Red-64.png", UriKind.Relative))

Like for me -> working is:

string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));


Try Stretch="UniformToFill" on the Image


Here is how it worked beautifully for me. In the window resources add the image.

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

Then the code goes like this.

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

"this" is referring to the Window object


Try Stretch="UniformToFill" on the Image


Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

Like for me -> working is:

string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));


Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?

Examples related to execution

Gradle to execute Java class (without modifying build.gradle) How to stop/terminate a python script from running? Adding delay between execution of two following lines php timeout - set_time_limit(0); - don't work .do extension in web pages? Oracle query execution time Can I pass an argument to a VBScript (vbs file launched with cscript)? How to force Sequential Javascript Execution? How to tell PowerShell to wait for each command to end before starting the next? Asynchronous vs synchronous execution, what does it really mean?