Setting Wpf Image Source in Code

Setting WPF image source in code

After having the same problem as you and doing some reading, I discovered the solution - Pack URIs.

I did the following in code:

Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;

Or shorter, by using another BitmapImage constructor:

finalImage.Source = new BitmapImage(
new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));

The URI is broken out into parts:

  • Authority: application:///
  • Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path

    • AssemblyShortName: the short name for the referenced assembly.
    • ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;component: specifies that the assembly being referred to is referenced from the local assembly.
    • /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.

The three slashes after application: have to be replaced with commas:

Note: The authority component of a pack URI
is an embedded URI that points to a
package and must conform to RFC 2396.
Additionally, the "/" character must
be replaced with the "," character,
and reserved characters such as "%"
and "?" must be escaped. See the OPC
for details.

And of course, make sure you set the build action on your image to Resource.

Change image source in code behind - Wpf

You just need one line:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));

How to programmatically set the Image source

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));

set image source in wpf

Try this, Works for me.

        var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(source.AbsoluteUri);
bitmap.EndInit();
return bitmap;

Full Source Code

  public MainWindow()
{
InitializeComponent();

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

string subpath = "UserProfile";
Directory.CreateDirectory(subpath);


// Set filter for file extension and default file extension
dlg.DefaultExt = ".jpg";
dlg.Filter = "jpeg Files (*.jpg)|*.jpg";
// Display OpenFileDialog by calling ShowDialog method
if (dlg.ShowDialog() == true)
{
string fileName = "pic" + txtEmployeeID.Text + ".jpg";
string newPath = "\\" + subpath + "\\" + fileName;

if (File.Exists(Directory.GetCurrentDirectory() + "\\" + newPath))
{
imgUser.Source = null;
File.Delete(Directory.GetCurrentDirectory() + newPath);
}

File.Copy(dlg.FileName.ToString(), Directory.GetCurrentDirectory() + "\\" + newPath);

ImageSource imageSrc = BitmapFromUri(new Uri(Directory.GetCurrentDirectory() + newPath));
imgUser.Source = imageSrc;

}





}

public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(source.AbsoluteUri);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

string subpath = "UserProfile";
Directory.CreateDirectory(subpath);


// Set filter for file extension and default file extension
dlg.DefaultExt = ".jpg";
dlg.Filter = "jpeg Files (*.jpg)|*.jpg";
// Display OpenFileDialog by calling ShowDialog method
if (dlg.ShowDialog() == true)
{
string fileName = "pic" + DateTime.Now.Millisecond + ".jpg";
string newPath = "\\" + subpath + "\\" + fileName;

if (File.Exists(Directory.GetCurrentDirectory() + "\\" + newPath))
{
imgUser.Source = null;
// File.Delete(Directory.GetCurrentDirectory() + newPath);
}

File.Copy(dlg.FileName.ToString(), Directory.GetCurrentDirectory() + "\\" + newPath);

ImageSource imageSrc = BitmapFromUri(new Uri(Directory.GetCurrentDirectory() + newPath));
imgUser.Source = imageSrc;

}
}

Xaml

 <Image x:Name="imgUser" Margin="88,70,49,72"> </Image>

<Button Margin="0,277,425,0" Click="Button_Click"> </Button>

Assign image source in code-behind of XAML control

Your "messy" code is pretty much the code you would need to add an item to a content control. You can't really shorten it, but if you're doing this regularly, refactoring to a method could help reduce the extra code required:

public void AddImageToContainer(string path, Panel parent)
{
var bmap = new BitmapImage(new Uri(_appPath + path, UriKind.RelativeOrAbsolute));
var img = new Image
{
Source = bmap,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Stretch = Stretch.None
};
parent.Children.Add(img);
}

You could then just call this as needed, ie:

AddImageToContainer("images/toplogo.png", StackPanelBanner);

Add an image source to ContentControl from C# code behind

try this :

myContentControl.Content=ACimage;


Related Topics



Leave a reply



Submit