保存图象到Sql Server,并且读取显示

现有图象数据表
CREATE TABLE [ENTR_Image] (
    
[EIGuid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__ENTR_Imag__EIGui__2C3F4C1F] DEFAULT (newid()),
    
[EImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__EImag__2D337058] DEFAULT (''),
    
[VImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__VImag__2E279491] DEFAULT (''),
    
[OperationTime] [datetime] NOT NULL CONSTRAINT [DF__ENTR_Imag__Opera__2F1BB8CA] DEFAULT (getdate()),
     
PRIMARY KEY  CLUSTERED 
    (
        
[EIGuid]
    )  
ON [PRIMARY] 
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO


需要把指定的图片添加到数据库里面
打开图片到pictureBox里面(需要把2张图片分别载入pictureBox)
    private void button1_Click(object sender, System.EventArgs e)
        
{
            OpenFileDialog oFileDialog1 
= new OpenFileDialog();
            oFileDialog1.InitialDirectory 
= "c:\\" ;
            oFileDialog1.Filter 
="Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
            oFileDialog1.FilterIndex 
= 1 ;
            oFileDialog1.RestoreDirectory 
= true ;
            
if(oFileDialog1.ShowDialog() == DialogResult.OK)
            
{
                
if(oFileDialog1.FileName != null)
                
{
                    
if (pictureBox1.Image!=null)
                    
{
                        
//MessageBox.Show("OK");
                        label4.Text=oFileDialog1.FileName; 
                        pictureBox2.Image
=Image.FromFile(oFileDialog1.FileName);
                        
return;
                    }

                    label3.Text
=oFileDialog1.FileName; 
                    
//textBox1.Text=oFileDialog1.FileName; 
                    pictureBox1.Image=Image.FromFile(oFileDialog1.FileName);
                
                }

            }

        }

保存图象到数据表
    private void button2_Click(object sender, System.EventArgs e)
        
{
            
//保存
            string filename =label3.Text;
            
byte [] content = ImageToStream(filename);
            
            
string filename1 =label4.Text;
            
byte [] content1 = ImageToStream(filename1);

            StoreImage(content,content1);
        }
其中用到如下方法:把指定文件名的图片转化为二进制流byte[]
    private byte[] ImageToStream(string fileName)
        
{
            Bitmap image 
= new Bitmap(fileName);
            MemoryStream stream 
= new MemoryStream();
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            
return stream.ToArray();
        }

保存byte[] 到数据表
    private void StoreImage(byte[] content,byte[] connect1)
        
{
//            if (MainForm.conn.State.Equals(ConnectionState.Closed)) 
//                MainForm.conn.Open();
            string str_Conn="server=SERVER-DBT;database=LogERP;uid=logerp;pwd=logerpok;Max Pool Size=20000;";
            
            
try
            
{
                SqlConnection sqlconn
=new SqlConnection(str_Conn);
                sqlconn.Open();
               
                SqlCommand insert 
= new SqlCommand("Insert into ENTR_Image(EImage,VImage) values (@EImage,@VImage)");
                insert.Connection
=sqlconn;
                SqlParameter imageParameter 
= 
                    insert.Parameters.Add(
"@EImage", SqlDbType.Binary);
                imageParameter.Value 
= content;
                imageParameter.Size  
= content.Length;

                SqlParameter imageParameter1 
= 
                    insert.Parameters.Add(
"@VImage", SqlDbType.Binary);
                imageParameter1.Value 
= connect1;
                imageParameter1.Size  
= connect1.Length;
                

                
int i=insert.ExecuteNonQuery();                
                sqlconn.Close();
                MessageBox.Show(i.ToString());

            }

            
catch(Exception ex)
            
{
                MessageBox.Show(ex.Message.ToString());
                MessageBox.Show(ex.StackTrace.ToString ()); 
            }

            
finally
            
{
//                MainForm.conn.Close();
            }

        }
 

新增以后根据Guid进行查询,图象
        private string str_Guid;
        
public string str_ImageGuid
        
{
            
set
            
{
                str_Guid
=value;
            }

        }

        private void ReadImage()
        
{
            
string str_Conn="server=172.17.100.132;database=Northwind;uid=sa;pwd=19791225;Max Pool Size=20000;";
            
try
            
{
                
//根据GUID读取图片
                SqlConnection sqlconn=new SqlConnection(str_Conn);
                sqlconn.Open();
                
string str_Sql="select EImage from ENTR_Image where EIGuid='"+str_Guid+"'";
                SqlCommand cmd
=new SqlCommand(str_Sql);
                cmd.Connection
=sqlconn;
                
byte [] content = (byte[] )cmd.ExecuteScalar();
                
try
                
{
                    MemoryStream stream 
= new MemoryStream(content);
                    pictureBox1.Image
= Image.FromStream(stream); 
                }

                
catch
                
{

                }



                str_Sql
="select VImage from ENTR_Image where EIGuid='"+str_Guid+"'";
                cmd
=new SqlCommand(str_Sql);
                cmd.Connection
=sqlconn;
                content 
= (byte[] )cmd.ExecuteScalar();
                
try
                
{
                    MemoryStream stream 
= new MemoryStream(content);
                    pictureBox2.Image
= Image.FromStream(stream); 
                }

                
catch
                
{
                }

                sqlconn.Close();
                
            }

            
catch (Exception ex)
            
{
                MessageBox.Show(ex.Message.ToString());
                MessageBox.Show(ex.StackTrace.ToString ()); 
            }

        }
byte[] 的初始化:
  byte[] byt={};
            ClassEnt_rsDrawing.Browser
=byt;

现在如果转换过来,把SQL里面的Image 字段的内容读入文件:
代码如下:
    /// <summary>
        
/// 根据2进制数组获得文件
        
/// </summary>
        
/// <param name="byt">2进制数据</param>
        
/// <param name="str_Filename">目标文件</param>

        private void GetFileFromDataBase(byte[] byt,string str_Filename)
        
{
            
//MemoryStream stream = new MemoryStream(byt);
            FileStream fs_stream=new FileStream(str_Filename,FileMode.CreateNew);
            BinaryWriter writefile 
= new BinaryWriter(fs_stream);
            writefile.Write(byt);
            writefile.Close();            
        }

辅助代码:
保存对话框
    /// <summary>
        
/// 另存为 保存文件对话框
        
/// </summary>
        
/// <returns></returns>

        private string fun_savefilename()
        
{
            
string savefilename="";
            SaveFileDialog saveFileDialog1 
= new SaveFileDialog(); 
            saveFileDialog1.Filter 
= "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*"  ;
            
            saveFileDialog1.FilterIndex 
= 1 ;
            saveFileDialog1.RestoreDirectory 
= true ;
            
            
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
            
{
                savefilename
=saveFileDialog1.FileName;                 
            }

            
return savefilename;
        }

把数据库里面的Image  读出到byte[]里面,代码:
这里Browser是Image 类型
    public byte[] GetImage(string str_Guid)
        
{
            
byte[] byt={};
            StringBuilder strSql
=new StringBuilder();
            strSql.Append(
"select Browser from rsDrawing ");
            
if(str_Guid.Trim()!="")
            
{
                strSql.Append(
" where Guid='"+str_Guid+"'");
            }

            byt
=DataBase.GetByteImage(strSql.ToString());            
            
return byt;
        }




    
/// <summary>
        
/// 根据Sql(完整)语句,获得Byte[]图片信息
        
/// </summary>
        
/// <param name="str_Sql">SQL语句</param>
        
/// <returns>二进制流</returns>

        public static byte[] GetByteImage(string str_Sql)
        
{            
            
string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnStr"].ToString();
            
byte [] content={};
            SqlConnection sqlconn
=new SqlConnection(connectionString);
            sqlconn.Open();            
            SqlCommand cmd
=new SqlCommand(str_Sql);
            cmd.Connection
=sqlconn;
            content 
= (byte[] )cmd.ExecuteScalar();
            sqlconn.Close();
            
return content;
        }

显示byte[] 到Form 里面
    /// <summary>
        
/// 显示图象到窗体
        
/// </summary>
        
/// <param name="byt_Image"></param>

        private void ImageLoad(byte[] byt_Image)
        
{
            DevExpress.XtraEditors.PictureEdit pb 
= new DevExpress.XtraEditors.PictureEdit();
            Form f
= new Form();
            f.Controls.Add(pb);
            f.MinimizeBox 
= false;
            f.MaximizeBox
=false;
            pb.Dock
=DockStyle.Fill;
            pb.Properties.SizeMode 
= DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch ;
            f.StartPosition 
= FormStartPosition.CenterScreen;
            pb.Properties.PictureStoreMode 
= DevExpress.XtraEditors.Controls.PictureStoreMode.ByteArray;
            pb.EditValue 
= byt_Image;
            f.Show();
        }
原文地址:https://www.cnblogs.com/jhtchina/p/341850.html