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

  • Question

  • Hi, Guys
    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

     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

    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 Software Developer

    Wednesday, September 18, 2013 6:04 PM

Answers

  • Hi,

    just change your photo attribute's datatype in the table to varbinary(MAX). and use the below code

                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));
                    using (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;
                        CV.photo = File.ReadAllBytes(op.FileName);
                        ////If you want the Image from Image control and then convert it to byte array
                        ////CV.photo = ConvertToBytes((photo.Source as BitmapImage));
                        entity.cvs.Add(CV);
                        entity.SaveChanges();
                    }
                }
    

    ConvertToBytes function used to convert bitmapimage to byte[]. It is incase if you take the image from image control.

    //Convert BitmapImage to byte[] array
            public static byte[] ConvertToBytes(BitmapImage bitmapImage)
            {
                byte[] data = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
                    wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
                    stream.Seek(0, SeekOrigin.Begin);
                    data = stream.GetBuffer();
                }
                return data;
            }

    To Retrieve from the SQL and Display in the Image control

    photo.Source = ToImage(CV.photo);

    ToImage Function:

        //Convert byte[] array to BitmapImage
            public BitmapImage ToImage(byte[] array)
            {
                using (var ms = new System.IO.MemoryStream(array))
                {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = ms;
                    image.EndInit();
                    return image;
                }
            }


    srithar

    Thursday, September 19, 2013 4:18 AM
  • Hi Mido,

    According to your description, I create a sample code to show you how to choose an image and upload it to database using ADO.NET Entity Framework.

    In the Click event of Browse button, I used System.Windows.Forms.OpenFileDialog control to browse images, display the image's name in TextBox:

    In the Upload button's Click event, note that the process of Entity Framework:

    private void SaveImage_Click(object sender, RoutedEventArgs e) 
    { 
                FileStream Stream = new FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read); 
                StreamReader Reader = new StreamReader(Stream); 
                Byte[] ImgData = new Byte[Stream.Length - 1]; 
                Stream.Read(ImgData, 0, (int)Stream.Length - 1); 
                using (dbtestEntities db = new dbtestEntities()) 
                { 
                    imageinfo o = db.imageinfoes.Create(); 
                    o.Name = GetFileNameNoExt(TextBox1.Text); 
                    o.ImgData = ImgData; 
                    db.imageinfoes.Add(o); 
                    db.SaveChanges(); 
                } 
     
                Label1.Content = GetFileNameNoExt(TextBox1.Text.Trim()) + " Stored Successfully...."; 
    }

    You could download this sample at Windows Dev Center:

    #WPF Upload Image Using ADO.NET Entity Framework
    http://code.msdn.microsoft.com/windowsdesktop/WPF-Upload-Image-Using-b8d1daed

    Please check the following references:

    #Get Started with Entity Framework (EF)
    http://msdn.microsoft.com/en-us/data/ee712907


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, September 18, 2013 8:17 AM
    Moderator

All replies



  • Tuesday, September 17, 2013 7:44 PM
  • hi,

    The following code will solve your problem.

    My Table Definition:

    # Table Definition
    
     
    
    CREATE TABLE [dbo].[ImageStore](
    
                    [id] [int] NOT NULL,
    
                    [name] [nvarchar](100) NOT NULL,
    
                    [image] [varbinary](max) NULL,
    
                    CONSTRAINT [pk_filestoredemo_id] PRIMARY KEY CLUSTERED ([id] ASC))
    
     
    
    # End Definition

    C# Code

     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));
                 
                    using (ImageEntities imageEntities = new ImageEntities())
                    {
                        ImageStore imgStore = imageEntities.ImageStore.CreateObject();
    
                        imgStore.name = new FileInfo(op.FileName).Name;
    
                        imgStore.content = File.ReadAllBytes(op.FileName);
    
                        imgStore.FileStoreDemoes.AddObject(imgStore);
    
                        imageEntities.SaveChanges();
    
                    }
                }



    srithar


    • Edited by Srithar Wednesday, September 18, 2013 7:04 AM
    Wednesday, September 18, 2013 7:03 AM
  • Hi Mido,

    According to your description, I create a sample code to show you how to choose an image and upload it to database using ADO.NET Entity Framework.

    In the Click event of Browse button, I used System.Windows.Forms.OpenFileDialog control to browse images, display the image's name in TextBox:

    In the Upload button's Click event, note that the process of Entity Framework:

    private void SaveImage_Click(object sender, RoutedEventArgs e) 
    { 
                FileStream Stream = new FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read); 
                StreamReader Reader = new StreamReader(Stream); 
                Byte[] ImgData = new Byte[Stream.Length - 1]; 
                Stream.Read(ImgData, 0, (int)Stream.Length - 1); 
                using (dbtestEntities db = new dbtestEntities()) 
                { 
                    imageinfo o = db.imageinfoes.Create(); 
                    o.Name = GetFileNameNoExt(TextBox1.Text); 
                    o.ImgData = ImgData; 
                    db.imageinfoes.Add(o); 
                    db.SaveChanges(); 
                } 
     
                Label1.Content = GetFileNameNoExt(TextBox1.Text.Trim()) + " Stored Successfully...."; 
    }

    You could download this sample at Windows Dev Center:

    #WPF Upload Image Using ADO.NET Entity Framework
    http://code.msdn.microsoft.com/windowsdesktop/WPF-Upload-Image-Using-b8d1daed

    Please check the following references:

    #Get Started with Entity Framework (EF)
    http://msdn.microsoft.com/en-us/data/ee712907


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, September 18, 2013 8:17 AM
    Moderator
  • Hi,

    just change your photo attribute's datatype in the table to varbinary(MAX). and use the below code

                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));
                    using (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;
                        CV.photo = File.ReadAllBytes(op.FileName);
                        ////If you want the Image from Image control and then convert it to byte array
                        ////CV.photo = ConvertToBytes((photo.Source as BitmapImage));
                        entity.cvs.Add(CV);
                        entity.SaveChanges();
                    }
                }
    

    ConvertToBytes function used to convert bitmapimage to byte[]. It is incase if you take the image from image control.

    //Convert BitmapImage to byte[] array
            public static byte[] ConvertToBytes(BitmapImage bitmapImage)
            {
                byte[] data = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
                    wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
                    stream.Seek(0, SeekOrigin.Begin);
                    data = stream.GetBuffer();
                }
                return data;
            }

    To Retrieve from the SQL and Display in the Image control

    photo.Source = ToImage(CV.photo);

    ToImage Function:

        //Convert byte[] array to BitmapImage
            public BitmapImage ToImage(byte[] array)
            {
                using (var ms = new System.IO.MemoryStream(array))
                {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = ms;
                    image.EndInit();
                    return image;
                }
            }


    srithar

    Thursday, September 19, 2013 4:18 AM
  • thanks;
    It's working :)

    Mohamed Safwat Software Developer

    Friday, September 20, 2013 2:40 PM
  • WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
    wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
    what is this SaveJpeg? i get an error. can you explain this a bit please?
    Sunday, November 15, 2015 1:54 PM
  • I was getting this error, after a bit of research I worked it this way...

    public static byte[] ConvertToBytes(BitmapImage bitmapImage)
            {
    
                 //Insert code Here
    
            }
            
            return data;
    }
    
    

    insert this code

    byte[] data = null;
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
    
    using (MemoryStream stream = new MemoryStream())
        {
           WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
           encoder.Save(stream);
           data = stream.ToArray();
        }

    Tuesday, August 28, 2018 2:21 PM