0

I have a picturebox called picture I want to get the image of this picturebox and save it as bitmapsource

BitmapSource myPic;
  myPic = picture.Image;

But i get this error :

Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Drawing.Image' to 'System.Windows.Media.Imaging.BitmapSource'

Ehsan Akbar
  • 6,977
  • 19
  • 96
  • 180

2 Answers2

1

You need to convert the System.Drawing.Image to a System.Drawing.Bitmap and next convert it to a BitmapSource.

You can pick one of this solutions: fast converting Bitmap to BitmapSource wpf

Community
  • 1
  • 1
1

use this method:

public BitmapSource ImageToBitmapSource(System.Drawing.Image image)
{
        var bitmap = new System.Drawing.Bitmap(image);

        var bitSrc =BitmapToBitmapSource(bitmap);

        bitmap.Dispose();
        bitmap = null;

        return bitSrc;
}

public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap source)
{
        BitmapSource bitSrc = null;

        var hBitmap = source.GetHbitmap();

        try
        {
            bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        catch (Win32Exception)
        {
            bitSrc = null;
        }

        return bitSrc;
}
Saeed Ahmadian
  • 1,112
  • 1
  • 10
  • 21