WPFのImage控制元件souce引入的方法總結
1、後臺程式碼相對路徑新增(若為絕對路徑,換UriKind的屬性即可)
BitmapImage testBitmapImage = new BitmapImage(new Uri(@"\bin\Sources\ON_btn_AutoDetect.bmp", UriKind.Relative));
image1.Source = imagetemp;
2、後臺程式碼二進位制新增
private string path = @"F:\1.jpg";
private void Window_Loaded(object sender, RoutedEventArgs e)
{
using (BinaryReader loader = new BinaryReader(File.Open(path, FileMode.Open)))
{
FileInfo fd = new FileInfo(path);
int Length = (int)fd.Length;
byte[] buf = new byte[Length];
buf = loader.ReadBytes((int)fd.Length);
loader.Dispose();
loader.Close();
//開始載入影象
BitmapImage bim = new BitmapImage();
bim.BeginInit();
bim.StreamSource = new MemoryStream(buf);
bim.EndInit();
image1.Source = bim;
GC.Collect(); //強制回收資源
}
3、前臺程式碼直接新增(圖片在專案中的檢視僅是檢視作用,其實已經放入原始碼某個資料夾下)
完整的協議:
編譯時知道的檔案:
<Image Source="pack://application:,,,/images/my.jpg"/>
執行才知道的檔案:(別的資源引用本程式集dll)
<Image Source="pack://siteoforigin:,,,/images/my.jpg"/>
(其中,,,表示是 ///的縮寫,當然也可以指定程式集)
示例:
<Image Source="Images/Desert.jpg"/>
4、後臺程式碼新增本地(電腦上)的圖片
try
{
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
StreamResourceInfo info = Application.GetRemoteStream(new Uri("pack://siteoforigin:,,,/" + e.NewValue.ToString(), UriKind.RelativeOrAbsolute));
bi.StreamSource = info.Stream;
bi.EndInit();
// Set the image source.
window.BgImage.Source = bi;
}
catch (UriFormatException ue)
{
ErrorMessage.Show(ERROR.FIND_PATH_ERRIMAGEURI+"錯誤資訊"+ue.ToString());
}
或者
window.BgImage.Source = new BitmapImage(new Uri("pack://siteoforigin:,,,/"+ e.NewValue.ToString(), UriKind.Absolute));