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

1.1k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

if you don't want to load, it means you want to create bitmap in runtime. if this, you can use this code:

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, 0, red, 200,10);
        flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
        red += 20;
        white += 20;
    }
    pictureBox1.Image = flag;
}

you can fill bitmap with anything you want, for example you can create bitmap by bits value that you saved in database