Ehsan Akbar
Ehsan Akbar

Reputation: 7281

Get bitmapsource from a picturebox in C#

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'

Upvotes: 0

Views: 1372

Answers (2)

Saeed Ahmadian
Saeed Ahmadian

Reputation: 1119

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

Upvotes: 1

Ariel Lenis
Ariel Lenis

Reputation: 101

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

Upvotes: 1

Related Questions