简体   繁体   中英

Displaying WriteableBitmap in Image in C# Visual Studio 2017

I'm using Visual Studio 2017. I've got a WriteableBitmap that I want to display to the user. To do that, I've got this component in my MainWindow.xaml :

<Image x:Name="FrameDisplayImage" Grid.Row="1" Stretch="Uniform"/>

Now I try to assign the image to the component like so in the MainWindow.xaml.cs :

FrameDisplayImage.Source = this.colorBitmap;

This doesn't work, the error is that the name FrameDisplayImage is not available in the current context.

I'm probably missing some include or connection between the xaml and the cs - but I'm completely new to C# and can't get it to work. Can someone point me in the right direction?

Create a method to convert bitmap to image source then you can display it on the wpf xaml like this.

FrameDisplayImage.Source = BitmapToImageSource(this.colorBitmap);

BitmapImage BitmapToImageSource(Bitmap bitmap)
{
    using (MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
        memory.Position = 0;
        BitmapImage bitmapimage = new BitmapImage();
        bitmapimage.BeginInit();
        bitmapimage.StreamSource = memory;
        bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapimage.EndInit();

        return bitmapimage;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM