C# WPF 图片资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/347614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF image resources
提问by driis
I come from a mostly web and a little bit Windows Forms background. For a new project, we will be using WPF. The WPF application will need 10 - 20 small icons and images for illustrative purposes. I am thinking about storing these in the assembly as embedded resources. Is that the right way to go?
我主要来自 Web 和一点 Windows 窗体背景。对于一个新项目,我们将使用 WPF。WPF 应用程序将需要 10 - 20 个小图标和图像用于说明目的。我正在考虑将这些作为嵌入式资源存储在程序集中。这是正确的方法吗?
How do I specify in XAML that an Image control should load the image from an embedded resource?
如何在 XAML 中指定图像控件应从嵌入资源加载图像?
采纳答案by Drew Noakes
If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image
elements.
如果您将在多个地方使用图像,那么值得将图像数据仅加载一次到内存中,然后在所有Image
元素之间共享。
To do this, create a BitmapSource
as a resource somewhere:
为此,请BitmapSource
在某处创建一个作为资源:
<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />
Then, in your code, use something like:
然后,在您的代码中,使用以下内容:
<Image Source="{StaticResource MyImageSource}" />
In my case, I found that I had to set the Image.png
file to have a build action of Resource
rather than just Content
. This causes the image to be carried within your compiled assembly.
就我而言,我发现我必须将Image.png
文件设置为具有构建操作,Resource
而不仅仅是Content
. 这会导致在编译的程序集中携带图像。
回答by ema
Yes, it is the right way.
是的,这是正确的方法。
You could use the image in the resource file just using the path:
您可以仅使用路径使用资源文件中的图像:
<Image Source="..\Media\Image.png" />
You must set the build action of the image file to "Resource".
您必须将图像文件的构建操作设置为“资源”。
回答by user42467
回答by Nuno Rodrigues
I found to be the best practice of using images, videos, etc. is:
我发现使用图像、视频等的最佳实践是:
- Change your files "Build action"to "Content". Be sure to check Copy to build directory.
- Found on the "Right-Click" menu at the Solution Explorer window.
- Image Sourcein the following format:
- "/?YourAssemblyName?;component/?YourPath?/?YourImage.png?"
- 将您的文件“构建操作”更改为“内容”。请务必选中Copy to build directory。
- 在解决方案资源管理器窗口的“右键单击”菜单上找到。
- 图像源采用以下格式:
- “/ YourAssemblyName?;组件/ YourPath /?YourImage.png? ”
Example
例子
<Image Source="/WPFApplication;component/Images/Start.png" />
Benefits:
好处:
- Files are not embedded into the assembly.
- The Resource Manager will raise some memory overflow problems with too many resources (at build time).
- Can be called between assemblies.
- 文件未嵌入到程序集中。
- 资源管理器会因资源过多(在构建时)引发一些内存溢出问题。
- 可以在程序集之间调用。
回答by techfan
Full description how to use resources: WPF Application Resource, Content, and Data Files
如何使用资源的完整说明:WPF 应用程序资源、内容和数据文件
And how to reference them, read "Pack URIs in WPF".
以及如何引用它们,请阅读“在 WPF 中打包 URI”。
In short, there is even means to reference resources from referenced/referencing assemblies.
简而言之,甚至可以通过引用/引用程序集来引用资源。
回答by Craig
Some people are asking about doing this in code and not getting an answer.
有些人要求在代码中执行此操作并没有得到答案。
After spending many hours searching I found a very simple method, I found no example and so I share mine here which works with images. (mine was a .gif)
花了很多时间搜索后,我找到了一个非常简单的方法,但没有找到任何示例,因此我在这里分享我的适用于图像的方法。(我的是.gif)
Summary:
概括:
It returns a BitmapFrame which ImageSource "destinations" seem to like.
它返回一个 BitmapFrame,ImageSource“目的地”似乎喜欢它。
Use:
用:
doGetImageSourceFromResource ("[YourAssemblyNameHere]", "[YourResourceNameHere]");
Method:
方法:
static internal ImageSource doGetImageSourceFromResource(string psAssemblyName, string psResourceName)
{
Uri oUri = new Uri("pack://application:,,,/" +psAssemblyName +";component/" +psResourceName, UriKind.RelativeOrAbsolute);
return BitmapFrame.Create(oUri);
}
Learnings:
学习:
From my experiences the pack string is not the issue, check your streams and especially if reading it the first time has set the pointer to the end of the file and you need to re-set it to zero before reading again.
根据我的经验,包字符串不是问题,请检查您的流,特别是如果第一次读取它已将指针设置为文件末尾并且您需要在再次读取之前将其重新设置为零。
I hope this saves you the many hours I wish this piece had for me!
我希望这可以为您节省我希望这件作品为我带来的许多时间!
回答by JoanComasFdz
- Visual Studio 2010 Professional SP1.
- .NET Framework 4 Client Profile.
- PNG image added as resource on project properties.
- New file in Resources folder automatically created.
- Build action set to resource.
- Visual Studio 2010 专业版 SP1。
- .NET Framework 4 客户端配置文件。
- 在项目属性中作为资源添加的 PNG 图像。
- 自动创建资源文件夹中的新文件。
- 构建操作集到资源。
This worked for me:
这对我有用:
<BitmapImage x:Key="MyImageSource" UriSource="Resources/Image.png" />
回答by Eric Ouellet
In code to load a resource in the executing assembly where my image Freq.png
was in the folder Icons
and defined as Resource
:
在执行程序集中加载资源的代码中,我的图像Freq.png
位于文件夹中Icons
并定义为Resource
:
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
I also made a function:
我还做了一个功能:
/// <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));
}
Usage (assumption you put the function in a ResourceHelper class):
用法(假设您将该函数放在 ResourceHelper 类中):
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
Note: see MSDN Pack URIs in WPF:pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
注意:请参阅WPF 中的 MSDN Pack URI:pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
回答by Raghulan Gowthaman
The following worked and the images to be set is resources in properties:
以下工作和要设置的图像是属性中的资源:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;
回答by Sanjay Ranavaya
Yes, it's the right way. You can use images in the Resource file using a path:
是的,这是正确的方法。您可以使用路径使用资源文件中的图像:
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Nname}" IsChecked="{Binding IsChecked}"/>
<Image Source="E:\SWorking\SharePointSecurityApps\SharePointSecurityApps\SharePointSecurityApps.WPF\Images\sitepermission.png"/>
<TextBlock Text="{Binding Path=Title}"></TextBlock>
</StackPanel>