将位图图像转换为SourceImage [复制]

时间:2021-06-12 09:00:51

This question already has an answer here:

这个问题在这里已有答案:

I'm using some code to show live video from a camera.

我正在使用一些代码来显示来自相机的实时视频。

In Windows Form (C#) the code worked fine, but in WPF application i getting an error in :

在Windows窗体(C#)中,代码工作正常,但在WPF应用程序中我收到错误:

Bitmap img = (Bitmap)eventArgs.Frame.Clone();
Image.Source = img;

the error was : connot convert System.Drawing.Bitmap to System.Wondows.Media.ImageSource. So i converted the Bitmap image using this code:

错误是:connot将System.Drawing.Bitmap转换为System.Wondows.Media.ImageSource。所以我使用以下代码转换了Bitmap图像:

public ImageSource imageSourceForImageControl(Bitmap BitmapImage)
{
ImageSourceConverter SourceImage = new ImageSourceConverter();
return (ImageSource)SourceImage.ConvertFrom(BitmapImage);
}

Then i got a System.NullReferenceException

然后我得到了一个System.NullReferenceException

Any idea what should i do??

知道我该怎么办?

PS : Im a Newbie with C# applications

PS:我是C#应用程序的新手

1 个解决方案

#1


0  

I was using this for quite some time, try this.

我用了很长时间,试试这个。

public ImageSource imageSourceForImageControl(Bitmap bitmap)
{
    using(MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, ImageFormat.Png);
        memory.Position = 0;
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();
        return (ImageSource)bitmapImage;
    }
}

#1


0  

I was using this for quite some time, try this.

我用了很长时间,试试这个。

public ImageSource imageSourceForImageControl(Bitmap bitmap)
{
    using(MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, ImageFormat.Png);
        memory.Position = 0;
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();
        return (ImageSource)bitmapImage;
    }
}