2

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;

         entity.cvs.Add(CV);
         entity.SaveChanges();

how can i save image from image control into database ?

thanks;

Mohamed Safwat
  • 75
  • 3
  • 12
  • 1
    [dont use image for sql server data types](http://stackoverflow.com/questions/4113294/is-there-a-big-technical-difference-between-varbinarymax-and-image-data-types) – jamesSampica Sep 18 '13 at 19:18

2 Answers2

4

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
        encoder.Frames.Add(BitmapFrame.Create(image));
        encoder.Save(stream);
        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);
Clemens
  • 123,504
  • 12
  • 155
  • 268
2

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.

Pawel
  • 31,342
  • 4
  • 73
  • 104