C# WPF image控件 圖片 Source
加載圖片的幾種方式
1、加載網絡圖片
<Image Source="http://example.com/path/to/image.jpg" Stretch="UniformToFill"/>
2、加載項目中的圖片
<Image Source="path/to/your/image.jpg" Stretch="UniformToFill"/>
圖片需先加入項目:

3、加載本地圖片(相對路徑)
<Image Source="pack://siteoforigin:,,,/imgs/1.jpg" />
在后臺代碼中,則寫成:
img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/imgs/1.jpg", UriKind.Absolute));
雖然是相對路徑,但是參數必須選擇 UriKind.Absolute。搞不懂。
這種寫法,圖片不必事先加入項目,只需要在程序運行時,該路徑下的圖片存在即可(如果圖片不存在,則程序直接崩潰并退出)

如果寫成:
img.Source = new BitmapImage(new Uri(@"imgs/1.jpg", UriKind.Relative));
則要求圖片必須先添加的項目的資源中,因為以上寫法是以下寫法的簡寫:
img.Source = new BitmapImage(new Uri(@"pack://application:,,,/imgs/1.jpg", UriKind.Absolute));
4、加載本地圖片(絕對路徑)
<Image Source="pack://siteoforigin:,,,/e:/imgs/1.jpg" />
路徑斜杠的兩張書寫格式:
img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/E:\\04Window.png", UriKind.Absolute)); 或 img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/E:/04Window.png", UriKind.Absolute));
可以直接寫文件路徑?:
img.Source = new BitmapImage(new Uri(@"E:\04 Window.png", UriKind.Absolute));
循環顯示文件夾中的圖片:
public partial class MainWindow : Window { string[] files = Directory.GetFiles(@"C:\Users\Administrator\source\repos\WpfApp3\bin\Debug\imgs"); int position = -1; public MainWindow() { InitializeComponent(); } private void btnPre_Click(object sender, RoutedEventArgs e) { } private void btnNext_Click(object sender, RoutedEventArgs e) { position++; if(position == files.Length) { position = 0; } img.Source = new BitmapImage(new Uri(files[position], UriKind.Absolute)); } }
或者(把文件路徑寫成相對路徑)
public partial class MainWindow : Window { string[] files = Directory.GetFiles(@".\imgs"); int position = -1; public MainWindow() { InitializeComponent(); } private void btnPre_Click(object sender, RoutedEventArgs e) { position--; if (position < 0) { position = files.Length - 1; } string str = Directory.GetCurrentDirectory(); img.Source = new BitmapImage(new Uri(str + files[position], UriKind.Absolute)); } private void btnNext_Click(object sender, RoutedEventArgs e) { position++; if(position == files.Length) { position = 0; } string str = Directory.GetCurrentDirectory(); img.Source = new BitmapImage(new Uri(str + files[position], UriKind.Absolute)); } }
或
public partial class MainWindow : Window { string[] files = Directory.GetFiles("imgs"); int position = -1; public MainWindow() { InitializeComponent(); //img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/Pics/mm.jpg", UriKind.Absolute)); } private void btnPre_Click(object sender, RoutedEventArgs e) { position--; if (position < 0) { position = files.Length - 1; } img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/" + files[position], UriKind.Absolute)); } private void btnNext_Click(object sender, RoutedEventArgs e) { position++; if(position == files.Length) { position = 0; } img.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/" + files[position], UriKind.Absolute)); } }

浙公網安備 33010602011771號