C# WPF Load image from embedded resource

Date: 2019-11-19
using System.IO;
using System.Reflection;
using System.Windows.Media.Imaging;

namespace Plugin.Resources
{
    public static class Resource
    {
        public static BitmapFrame GreenImage { get; private set; }
        public static BitmapFrame RedImage { get; private set; }

        public static void LoadBitmapsInCurrentThread()
        {
            GreenImage = LoadBitmapFromResource("Plugin.Resources.green.png");
            RedImage = LoadBitmapFromResource("Plugin.Resources.red.png");
        }

        private static BitmapFrame LoadBitmapFromResource(string resourceName)
        {
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                var bitmapFrame = BitmapFrame.Create(stream, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
                bitmapFrame.Freeze();
                return bitmapFrame;
            }
        }
    }
}

Using Compile type Resource iso Embedded Resource, just use Uri’s

this.image.Source = new Uri("/Image.png", UriKind.Relative);
// using System.Windows;
        private static BitmapFrame LoadBitmapFromResource(Uri resourceUri)
        {
            using (StreamResourceInfo info = Application.GetContentStream(resourceUri);)
            {
                var bitmapFrame = BitmapFrame.Create(info.stream, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
                bitmapFrame.Freeze();
                return bitmapFrame;
            }
        }

https://docs.microsoft.com/en-us/dotnet/framework/wpf/app-development/wpf-application-resource-content-and-data-files

28940cookie-checkC# WPF Load image from embedded resource