C operation image reading and storage SQLserver implementation code

  • 2020-05-09 19:08:49
  • OfStack

1. Convert Image to byte[] with C# and insert into the database:
1.1 convert Image of picture control to stream:
 
private byte[] PicToArray() 
{ 
Bitmap bm = new Bitmap(picBox.Image); 
MemoryStream ms = new MemoryStream(); 
bm.Save(ms, ImageFormat.Jpeg); 
return ms.GetBuffer(); 
} 

 
        
    // Save to database  
      try 
{ 
string sql = "update T_Employee set ImageLogo=@ImageLogo where EmpId=@EmpId"; 
SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@ImageLogo", imgSourse)); 
MessageBox.Show(" Modification saved! ");// ShowInfo(0); 
} 
catch (Exception ex) 
{ 
MessageBox.Show(" Update failed! " + ex.Message); 
return; 
} 

1.2 convert the image file into a byte stream and insert it into the database:
 
class ImageInserter 
{ 
public static int InsertImg(string path) 
{ 
//---------- The image is read as a file and converted into a byte stream  
FileStream fs = new FileStream(path,FileMode.Open); 
byte[] imgSourse = new byte[fs.Length]; 
fs.Read(imgSourse,0,imgSourse.Length); 
fs.Close(); 
using (SqlConnection conn = new SqlConnection(SqlHelper.connStr)) 
{ 
conn.Open(); 
using (SqlCommand cmd = conn.CreateCommand()) 
{ 
cmd.CommandText = "update T_Employee set ImageLogo=@ImageLogo"; 
// cmd.Parameters.Add("@ImageLogo", SqlDbType.Image); 
cmd.Parameters.Add(new SqlParameter("@ImageLogo", imgSourse)); 
return cmd.ExecuteNonQuery(); 
} 
} 
} 

2. Extract image data from SQLserver and display it on pictureBox control:
 
       byte[] ImageLogoArray = row["ImageLogo"] is DBNull ? null :(byte[])(row["ImageLogo"]); 
MemoryStream ms=null; 
if (ImageLogoArray!=null) 
{ 
ms = new MemoryStream(ImageLogoArray); 
picBox.Image = new Bitmap(ms); 
} 

Related articles: