Save and retrieve Image c#

  • 297 Views
  • Last Post 06 December 2018
Stylus STYLUS posted this 04 December 2018

I have app, but have some simple solution. Using this code to insert into sql and working fine.

But i have 2000 employees and have a problem with the database too big when put inside the pictures of all workers i need some help or solution, to save some location with file name exmp. c:\some folder\imageofemployee.jpg when click on datagrid row (selection changed) to show picture from that location not put in sql image, just file location.

Some help??? I hope to good explain

//Insert into sql  

 byte[] img_arr = null;  
            MemoryStream ms = new MemoryStream();  
            //dataPictureBox.Image.Save(ms, dataPictureBox.Image.RawFormat);

            bool isNullOrEmpty = pictureBox1 == null || pictureBox1.Image == null;  
            if (!isNullOrEmpty)  
                pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);  

            img_arr = ms.GetBuffer();           

                    using (SqlConnection openCon = new SqlConnection(cs))  
                    {  
                        string saveStaff = "declare @maxNo integer = 0 select @maxNo = isnull(max(redni_broj), 0) from [dbo].[radnici]; Set @[email protected]+1;  INSERT INTO dbo.radnici (redni_broj, data) VALUES (@maxNo,@data)";  

                        using (SqlCommand querySaveStaff = new SqlCommand(saveStaff))  
                        {  
                            querySaveStaff.Connection = openCon;                             
                            querySaveStaff.Parameters.AddWithValue("@data", img_arr);  
                            openCon.Open();  
                            querySaveStaff.ExecuteNonQuery();  
                            openCon.Close(); 
                        }
admin posted this 06 December 2018

You should create an Employee class

For example:

public byte[] ImageToByteArray(Image img)
{
   using (var ms = new MemoryStream())
   {
      img.Save(ms,img.RawFormat);
      return  ms.ToArray();
   }
}

public class Employee
{
    public string EmployeeID {get; set;}
    public string FileName { get; set; }
    public byte[] Image{
        get{
           if(File.Exists(FileName))
               return ImageToByteArray(Image.FromFile(FileName));
           return null;
        }
    }
}

Save image URL to your SQL database, then retrieve the Employee list from SQL database

Next, add a bindingsource to your DataGridView, then you can see the image automatically show in the DataGridView

I hope you can solve your problem

Close