Search code examples
c#wpf.net-assemblyembedded-resourcebitmapsource

BitmapSource from embedded image


My goal is to draw image "someImage.png", which is embedded resource, on WPF window, in overridden OnRender method:

protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
    base.OnRender(drawingContext);            
    drawingContext.DrawImage(ImageSource, Rect);            
}

I found code to get my image from resources to Stream:

public BitmapSource GetSourceForOnRender()
{
    System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
    Stream myStream = myAssembly.GetManifestResourceStream("KisserConsole.someImage.png");

    // What to do now?

    return //BitmapSource    

}

But how can i get or create BitmapSource now?


Solution

  • You can create a BitmapImage from the stream by setting its StreamSource property:

    public BitmapSource GetSourceForOnRender()
    {
        var assembly = System.Reflection.Assembly.GetExecutingAssembly();
        var bitmap = new BitmapImage();
    
        using (var stream =
            assembly.GetManifestResourceStream("KisserConsole.someImage.png"))
        {
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.EndInit();
        }
    
        return bitmap;    
    }
    

    That said, you would usually create a BitmapImage from a Resource File Pack URI, like e.g.

    new BitmapImage(new Uri(
        "pack://application:,,,/KisserConsole.someImage.png"));