将图片以流的形式保存到数据库(Image)以及从数据库中取出显示

 

将图片以流的形式保存到数据库(Image)以及从数据库中取出显示 
try  
            { 
                
string  imagepath  =   @" D:\backImage\black.jpg "
                FileStream fs 
=   new  FileStream(imagepath, FileMode.Open); 
                BinaryReader br 
=   new  BinaryReader(fs); 
                
byte [] myimages  =  br.ReadBytes(Convert.ToInt32(fs.Length)); 
                
// string conn_Str = @"server=.;database=pubs;user=sa;pwd=sasa"; 
                 string  conn_Str  =   @" Data Source=DF15D10F40A945C\SQLEXPRESS;Initial catalog =pubs;user=sa;pwd=sasa "
                
using  (SqlConnection sqlcon  =   new  SqlConnection(conn_Str)) 
                { 
                    sqlcon.Open(); 
                    
string  insertsql  =   " insert into table1 values(1,@image) "
                    
using  (SqlCommand sqlcom  =   new  SqlCommand(insertsql, sqlcon)) 
                    { 
                        SqlParameter sqlparameter 
=   new  SqlParameter( " @image " , SqlDbType.Image); 
                        sqlparameter.Value 
=  myimages; 
                        sqlcom.Parameters.Add(sqlparameter); 
                        sqlcom.ExecuteNonQuery(); 
                    } 
                    
string  selectsql  =   " select * from table1 "
                    
using  (SqlCommand sqlcom  =   new  SqlCommand(selectsql, sqlcon)) 
                    { 
                        SqlDataReader sqldr 
=  sqlcom.ExecuteReader(); 
                        sqldr.Read(); 
                        
byte [] images  =  ( byte [])sqldr[ " myimage " ]; 
                        Stream stream 
=   new  MemoryStream(images); 
                        pictureBox2.Image 
=  System.Drawing.Image.FromStream(stream); 
                    } 
                } 
            } 
            
catch  (Exception ex) 
            { 
                MessageBox.Show(ex.Message); 
            } 

 

转载于:https://www.cnblogs.com/skyrickie/articles/1392030.html

你可能感兴趣的:(将图片以流的形式保存到数据库(Image)以及从数据库中取出显示)