Mohamed Safwat
Mohamed Safwat

Reputation: 75

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

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;

Upvotes: 2

Views: 7724

Answers (2)

Clemens
Clemens

Reputation: 128060

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

Upvotes: 4

Pawel
Pawel

Reputation: 31610

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.

Upvotes: 2

Related Questions