How to insert image from image control into WPF to SQL Database using entity data model

.net c# entity-framework sql-server wpf


i am creating an app to save student information into SQL , I want to know how to insert image from image control in WPF using entity framework to SQL database

i made event to upload image into image control and now i need to save it to sql database using entity framework

image load button code :

private void uploadbt_Click(object sender, RoutedEventArgs e)
     OpenFileDialog op = new OpenFileDialog();
     op.Title = "Select a picture";
     op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
         "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
         "Portable Network Graphic (*.png)|*.png";
     if (op.ShowDialog() == true)
         photo.Source = new BitmapImage(new Uri(op.FileName));

this is my database named cv

enter image description here

this is my code to save some information into database this cose for save button

facultymakerEntities1 entity = new  facultymakerEntities1();

         cv CV = new cv();
         CV.Full_Name = fullnametb.Text;
         CV.Activities = activitestb.Text;
         CV.Address = addresstb.Text;
         CV.Birth_Day = bddate.SelectedDate.Value;
         CV.Courses = cousetb.Text;
         CV.E_Mail = emailtb.Text;


how can i save image from image control into database ?


9/18/2013 6:57:37 PM

Accepted Answer

You will most certainly store an encoded image as byte[]. The following method creates a PNG frame from a BitmapSource:

private byte[] BitmapSourceToByteArray(BitmapSource image)
    using (var stream = new MemoryStream())
        var encoder = new PngBitmapEncoder(); // or some other encoder
        return stream.ToArray();

As you put BitmapImages to your Image's Source, you may simply pass that to this method:

var imageBuffer = BitmapSourceToByteArray((BitmapSource)photo.Source);
3/13/2017 10:36:23 AM

Popular Answer

Image in SqlServer is "Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes". In EF you need to have a property of byte[] type which can be mapped to a column of image type in SqlServer. When you load your image from disk don't load it to the BitmapImage but to a byte array, set the property accordingly and .SaveChanges() to store it in the database. If you want to show the image to the user load it from the database as byte array and then create a BitmapImage instance. You probably would have to use BimatpImage.StreamSource property to do that.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow