来自嵌入式图像的BitmapSource

时间:2015-03-22 18:25:24

标签: c# wpf .net-assembly embedded-resource bitmapsource

我的目标是在WPF窗口上以重写的OnRender方法绘制图像" someImage.png",这是嵌入式资源:

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

我找到了将资源从资源转移到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    

}

但是我现在如何获得或创建BitmapSource?

2 个答案:

答案 0 :(得分:6)

您可以通过设置其StreamSource属性

从流中创建BitmapImage
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;    
}

那就是说,你通常会从Resource File Pack URI创建一个BitmapImage,比如说。

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

答案 1 :(得分:0)

您可以尝试使用此功能:

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

BitmapImage bitmap = new BitmapImage( uri );

确保将图像文件的“生成操作”设置为“资源”。

相关问题