Search code examples
c#wpfbitmappictureboximagesource

WPF .NET Core App - Load bitmap to ui Image without saving it first - C#


I am trying to switch to the new WPF app style and so far I'm very unimpressed.

Is there a way to load a Bitmap which was generated by the application into a PictureBox without saving it first? So far I've found the following solution (which I want to improve):
UI: enter image description here

Xaml code:

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

UI-update code:

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

However, I'm very unpleased to save an image every few ms to disk so that I can display it in my Application. Is there any direct, fast way?

old, Winform Style

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

You can imagine, IO-Operations on a Video Converting Disk is not really optimal for Hard drive performance, especially on older, spinning hard drives.


Solution

  • Solution: "save" bitmap to memory stream and load stream

    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;
    }