load image in winforms using pack uri

2019-02-27 13:39发布

问题:

I have a problem trying to show some images on my winform. On one form, I have an wpf container, which has a WPF control that has no problem to load images from an external exe (that have the images as resources), which references the dll that contains the form, with the wpf container, that shows them.

Now, I want to add another winform, and I need to show there, the same images that are shown using the wpf container, but I cannot add a wpf container to this form, because I need to show the images on a combobox.

How can I load this images using URI pack, or how I turn this uri to something that I can use from my winform.

example uri.

pack://application:,,,/myPack;component/Images/image.png

回答1:

What you want to do is read the image data for use in Winforms, so you need direct access to the embedded resource image file, which can be done thusly:

Uri uri = new Uri("pack://application:,,,/myPack;component/Images/image.png", UriKind.RelativeOrAbsolute);
StreamResourceInfo info = Application.GetContentStream(uri);
System.Drawing.Image myImage = System.Drawing.Image.FromStream(info.Stream);

Edit: If you get an exception about invalid port, make sure you've registered the pack scheme, which you can do merely by referencing it. So put this line of code before the above:

string s = System.IO.Packaging.PackUriHelper.UriSchemePack; 


回答2:

Note!!

You should use this:

Application.GetResourceStream(uri);

Instead of this:

Application.GetContentStream(uri);

Because Content will not work for image file.



标签: c# .net wpf uri