BitmapSource from embedded image

匆匆过客 提交于 2019-12-01 18:14:21

问题


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?


回答1:


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"));



回答2:


You can try to use this:

Uri uri = new Uri( $"pack://application:,,,/YourAssemblyName;component/Resources/images/photo.png", UriKind.Absolute );

BitmapImage bitmap = new BitmapImage( uri );

Make sure the Build Action of the image file is set to Resource.



来源:https://stackoverflow.com/questions/29198137/bitmapsource-from-embedded-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!