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));