Dynamically adding and loading image from Resources in C#

后端 未结 5 1860
太阳男子
太阳男子 2020-12-19 02:31

I have some images added to my solution, right now it is under the folder images\\flowers\\rose.png inside the solution explorer. I want a way to dynamically load this imag

相关标签:
5条回答
  • 2020-12-19 03:11

    The following works just fine for me:

    image.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/Resources/someimage.png", UriKind.Absolute));
    

    Also you should change the Build Action of your image from None to Resource.

    0 讨论(0)
  • 2020-12-19 03:11

    You can open the Resource Editor (Solution Explorer, click on Resources.resx) and add the image there. Then you can simply access it as Bitmap with Properties.Resources.ImageId

    http://msdn.microsoft.com/en-us/library/3bka19x4(v=vs.100).aspx

    0 讨论(0)
  • 2020-12-19 03:17

    I had some problems to find the exact syntax for the URI, so see below more details :

    If your image (myImage.png) is located in a subfolder "images" (from the root directory) , the exact syntax is :

    image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/myImage.png", UriKind.Absolute));
    

    If your image is in the subfolder images/icon/ (from the root directory) , the syntax is :

    image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/icon/myImage.png", UriKind.Absolute));
    
    • Note that the part "pack://application:,,, does not change.
    • Be sure to set the "Build action" to "Resources"

    For more information: see here.

    0 讨论(0)
  • 2020-12-19 03:19

    You use this :

     Image2.Source = new Bitmap(
          System.Reflection.Assembly.GetEntryAssembly().
            GetManifestResourceStream("MyProject.Resources.myimage.png"));
    

    Or

    Image2.Source = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
    

    I do recommend the second one.

    0 讨论(0)
  • 2020-12-19 03:33

    The way you are adding image and then changing its "Build action" to "Resources" will also do the job, But as you have asked for adding and loading from Resources wold be a different approach to achieve the same task. I would liketo provide you a link to read certain msdn articles.

    Adding and Editing Resources (Visual C#)

    0 讨论(0)
提交回复
热议问题