WPF .NET Core应用程序-将位图加载到ui图像而不先保存-C#

问题描述

我正尝试切换到新的WPF应用程序样式,到目前为止,我对非常印象深刻。

有没有一种方法可以将应用程序生成的位图加载到PictureBox中而不先保存它?到目前为止,我已经找到了以下解决方案(需要改进):
用户界面:

enter image description here

Xaml代码

<Image x:Name="CurrentFrame_image" HorizontalAlignment="Left" Height="110" Margin="10,10,0" VerticalAlignment="Top" Width="190" Grid.ColumnSpan="2"/>

UI更新代码

public void UpdateProgressFrame(Bitmap currentScreen)
{
    currentScreen.Save(@".\progressframe.png");
    BitmapImage image = new BitmapImage(new Uri("/progressframe.png",UriKind.Relative));
    CurrentFrame_image.source = image;
}

但是,我非常不高兴每隔几毫秒将图像保存到磁盘上,以便可以在应用程序中显示它。有没有直接,快速方法

旧的Winform样式

public void UpdateProgressFrame(Bitmap currentScreen)
{
    CurrentFrame_pictureBox.Image = currentScreen;
}

您可以想象,视频转换磁盘上的IO操作对于硬盘驱动器性能并不是真正理想的,尤其是在较旧的旋转硬盘驱动器上。

解决方法

如果您不想加载,则意味着您要在运行时创建位图。 如果是这样,您可以使用以下代码:

PictureBox pictureBox1 = new PictureBox();
public void CreateBitmapAtRuntime()
{
    pictureBox1.Size = new Size(210,110);
    this.Controls.Add(pictureBox1);

    Bitmap flag = new Bitmap(200,100);
    Graphics flagGraphics = Graphics.FromImage(flag);
    int red = 0;
    int white = 11;
    while (white <= 100) {
        flagGraphics.FillRectangle(Brushes.Red,red,200,10);
        flagGraphics.FillRectangle(Brushes.White,white,10);
        red += 20;
        white += 20;
    }
    pictureBox1.Image = flag;
}

您可以用所需的任何内容填充位图,例如,可以通过保存在数据库中的位值来创建位图

,

解决方案: “保存”位图到内存流并加载流

BitmapImage BitmapToImageSource(ref Bitmap input)
{
    BitmapImage bitmapimage = new BitmapImage();
    using (MemoryStream memory = new MemoryStream())
    {
        input.Save(memory,System.Drawing.Imaging.ImageFormat.Bmp);
        memory.Position = 0;

        bitmapimage.BeginInit();
        bitmapimage.StreamSource = memory;
        bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapimage.EndInit();
    }

    return bitmapimage;
}