如何从生成动作标记为Resource的图像中获取System.Drawing.Image对象? [英] How to get a System.Drawing.Image object from image which build action is marked as Resource?
问题描述
我有一个wpf应用程序,并且有一个对代码隐藏有用的图像,该图像在项目中的位置类似于"projectName \ images \ pp.png",其构建动作为资源"(节点:非嵌入式资源).我在后面的代码中需要一个System.Drawing.Image对象.我尝试了以下方法:
I have a wpf app,and got a image useful for codebehind which's location in the project is something like "projectName\images\pp.png" and its build action is "Resource"(Node:not Embedded Resource). I need a System.Drawing.Image object in the codebehind. I tried these methods:
1.
var img = new BitmapImage(new Uri(@"\images\pp.png", UriKind.Relative));
var stream = img.StreamSource;
System.Drawing.Image needObj = Image.FromStream(stream);
我有一个空流,所以它不起作用.
i got a null stream,so it's not work.
2.
private static System.IO.Stream getResource(string name)
{
var assembly = Assembly.GetExecutingAssembly();
string resName = assembly.GetName().Name + ".g.resources";
return assembly.GetManifestResourceStream(resName);
}
var stream = getResource(@"\images\pp.png");
System.Drawing.Image needObj = Image.FromStream(stream);
我得到了一个UnmanagedMemoryStream对象,并且在调用"Image.FromStream(stream)"时发生了InvalidArgument异常.
i got an UnmanagedMemoryStream object,and an InvalidArgument exception occurred while calling "Image.FromStream(stream)" .
任何人都可以告诉我为什么上述两种方法不起作用或如何实现吗?
Could anyone tell me why the two methods above not working or how to achieve it ?
推荐答案
WPF-获取图像资源并转换为System.Drawing.Image
var bitmapImage = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "images/pp.png", UriKind.Absolute));
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)bitmapImage));
var stream = new MemoryStream();
encoder.Save(stream);
stream.Flush();
var image = new System.Drawing.Bitmap(stream);
注意:
- 使用"/"代替"\"
- 考虑阅读在WPF中打包URI (重要部分:资源文件包URI)
- 添加对system.drawing.dll的引用
- Use "/" instead of "\"
- Consider reading Pack URIs in WPF (important part: Resource File Pack URIs)
- Add reference to system.drawing.dll
本地程序集资源文件
已编译到本地的资源文件的包URI.程序集使用以下权限和路径: pack://application:,,,/ReferencedAssembly; component/Subfolder/ResourceFile.Ext
The pack URI for a resource file that is compiled into the local
assembly uses the following authority and path:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.Ext
这篇关于如何从生成动作标记为Resource的图像中获取System.Drawing.Image对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!