WilliamV
WilliamV

Reputation: 77

Convert drawing.bitmap to windows.controls.image

I am reading data from a smartcard. This data contains a picture as well. Code to get the picture in a class ReadData:

public Bitmap GetPhotoFile()
    {
        byte[] photoFile = GetFile("photo_file");
        Bitmap photo = new Bitmap(new MemoryStream(photoFile));
        return photo;
    }

Code in the xaml:

imgphoto = ReadData.GetPhotoFile();

Error being generated:
Cannot implicitly convert type 'System.Drawing.Bitmap' to 'System.Windows.Controls.Image'

What is the best approach in this?

Upvotes: 2

Views: 4918

Answers (1)

Clemens
Clemens

Reputation: 128013

Do not create a System.Drawing.Bitmap from that file. Bitmap is WinForms, not WPF.

Instead, create a WPF BitmapImage

public ImageSource GetPhotoFile()
{
    var photoFile = GetFile("photo_file");
    var photo = new BitmapImage();

    using (var stream = new MemoryStream(photoFile))
    {
        photo.BeginInit();
        photo.CacheOption = BitmapCacheOption.OnLoad;
        photo.StreamSource = stream;  
        photo.EndInit();
    }

    return photo;
}

Then assign the returned ImageSource to the Source property of the Image control:

imgphoto.Source = ReadData.GetPhotoFile();

Upvotes: 6

Related Questions