Dre*_*kes 463
如果您将在多个位置使用图像,那么将图像数据仅加载到内存中然后在所有Image元素之间共享它是值得的.
为此,BitmapSource 在某处创建一个资源:
<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />
Run Code Online (Sandbox Code Playgroud)
然后,在您的代码中,使用以下内容:
<Image Source="{StaticResource MyImageSource}" />
Run Code Online (Sandbox Code Playgroud)
就我而言,我发现我必须将Image.png文件设置为具有构建操作Resource而不仅仅是Content.这会导致图像在编译的程序集中携带.
Nun*_*ues 168
我发现使用图像,视频等的最佳做法是:
<Image Source="/WPFApplication;component/Images/Start.png" />
Run Code Online (Sandbox Code Playgroud)
优点:
小智 46
有些人要求在代码中执行此操作而不是得到答案.
经过几个小时的搜索,我找到了一个非常简单的方法,我找不到任何例子,所以我在这里分享我的图像.(我的是.gif)
摘要:
它返回一个ImageSource"目的地"似乎喜欢的BitmapFrame.
使用:
doGetImageSourceFromResource ("[YourAssemblyNameHere]", "[YourResourceNameHere]");
Run Code Online (Sandbox Code Playgroud)
方法:
static internal ImageSource doGetImageSourceFromResource(string psAssemblyName, string psResourceName)
{
Uri oUri = new Uri("pack://application:,,,/" +psAssemblyName +";component/" +psResourceName, UriKind.RelativeOrAbsolute);
return BitmapFrame.Create(oUri);
}
Run Code Online (Sandbox Code Playgroud)
学习:
根据我的经验,包字符串不是问题,请检查您的流,特别是如果第一次读取它已将指针设置为文件的末尾,您需要在再次读取之前将其重新设置为零.
我希望这可以节省你希望这件作品给我的好几个小时!
Eri*_*let 41
在代码中加载执行程序集中的资源,其中我的图像Freq.png位于文件夹中Icons并定义为Resource:
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
Run Code Online (Sandbox Code Playgroud)
我也做了一个功能:
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
Run Code Online (Sandbox Code Playgroud)
用法(假设您将函数放在ResourceHelper类中):
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
Run Code Online (Sandbox Code Playgroud)
注意:请参阅WPF中的MSDN包URI:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
ema*_*ema 39
是的,这是正确的方式.
您可以使用路径使用资源文件中的图像:
<Image Source="..\Media\Image.png" />
Run Code Online (Sandbox Code Playgroud)
您必须将映像文件的构建操作设置为"资源".
这为我工作:
<BitmapImage x:Key="MyImageSource" UriSource="Resources/Image.png" />
Run Code Online (Sandbox Code Playgroud)