zahra
zahra

Reputation: 1

How can I display a recovered image from sql on image control in wpf?

I put my pictures of letters in a separate table and I defined an foriegn key for that I now want to click on any data in the data grid view to show the photos of that level in the control of the image. I wrote the order for the retrieval of the photos, Of course, I do not know if it's right and I do not know how to control the image. code

        SqlConnection imageConnection = new SqlConnection(@"Data Source = ZAHRA; Initial Catalog = Baygani; inte");

        SqlCommand imageCommand = new SqlCommand(@"select Pictures.pic1,Pictures.pic2,Pictures.pic3,Pictures.pic4,Pictures.pic5,Pictures.pic6,Pictures.pic7,Pictures.pic8,Pictures.pic9,
         Pictures.pic10 from Pictures,Latters where Pictures.idlatter=Latters.id ", imageConnection);

        imageConnection.Open();
        SqlDataReader imageReader = imageCommand.ExecuteReader();

        string imageFilename = (string)imageReader.GetValue(0);
        byte[] imageBytes = (byte[])imageReader.GetValue(1);
        MemoryStream ms = new MemoryStream(imageBytes);

Upvotes: 0

Views: 59

Answers (1)

Wr4thon
Wr4thon

Reputation: 554

Assuming that you are using Bindings to display your data in your UI and thus using viewmodels, I would suggest utilizing an ImageSource.

To initialize an ImageSource from a byte array I wrote the following method:

public ImageSource LoadImageSourceFromBytes(byte[] imageBytes)
{
    BitmapImage bitmapImage = new BitmapImage();

    using (MemoryStream imageStream = new MemoryStream(imageBytes))
    {
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = imageStream;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();
    }

    bitmapImage.Freeze();

    return bitmapImage;
}

Upvotes: 1

Related Questions