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

本文介绍了一种在C#中实现图片数据与数据库交互的方法,包括将图片加载到PictureBox控件、图片数据的读写、图片保存到数据库及从数据库读取图片等功能。
现有图象数据表
None.gifCREATE TABLE [ENTR_Image] (
None.gif    
[EIGuid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__ENTR_Imag__EIGui__2C3F4C1F] DEFAULT (newid()),
None.gif    
[EImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__EImag__2D337058] DEFAULT (''),
None.gif    
[VImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__VImag__2E279491] DEFAULT (''),
None.gif    
[OperationTime] [datetime] NOT NULL CONSTRAINT [DF__ENTR_Imag__Opera__2F1BB8CA] DEFAULT (getdate()),
None.gif     
PRIMARY KEY  CLUSTERED 
None.gif    (
None.gif        
[EIGuid]
None.gif    )  
ON [PRIMARY] 
None.gif
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
None.gif
GO
None.gif
None.gif
None.gif
需要把指定的图片添加到数据库里面
打开图片到pictureBox里面(需要把2张图片分别载入pictureBox)
None.gif    private void button1_Click(object sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            OpenFileDialog oFileDialog1 
= new OpenFileDialog();
InBlock.gif            oFileDialog1.InitialDirectory 
= "c:\\" ;
InBlock.gif            oFileDialog1.Filter 
="Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
InBlock.gif            oFileDialog1.FilterIndex 
= 1 ;
InBlock.gif            oFileDialog1.RestoreDirectory 
= true ;
InBlock.gif            
if(oFileDialog1.ShowDialog() == DialogResult.OK)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(oFileDialog1.FileName != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (pictureBox1.Image!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
//MessageBox.Show("OK");
InBlock.gif
                        label4.Text=oFileDialog1.FileName; 
InBlock.gif                        pictureBox2.Image
=Image.FromFile(oFileDialog1.FileName);
InBlock.gif                        
return;
ExpandedSubBlockEnd.gif                    }

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

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

保存图象到数据表
None.gif    private void button2_Click(object sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
//保存
InBlock.gif
            string filename =label3.Text;
InBlock.gif            
byte [] content = ImageToStream(filename);
InBlock.gif            
InBlock.gif            
string filename1 =label4.Text;
InBlock.gif            
byte [] content1 = ImageToStream(filename1);
InBlock.gif
InBlock.gif            StoreImage(content,content1);
ExpandedBlockEnd.gif        }
其中用到如下方法:把指定文件名的图片转化为二进制流byte[]
None.gif    private byte[] ImageToStream(string fileName)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            Bitmap image 
= new Bitmap(fileName);
InBlock.gif            MemoryStream stream 
= new MemoryStream();
InBlock.gif            image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
InBlock.gif            
return stream.ToArray();
ExpandedBlockEnd.gif        }

None.gif
保存byte[] 到数据表
None.gif    private void StoreImage(byte[] content,byte[] connect1)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif
//            if (MainForm.conn.State.Equals(ConnectionState.Closed)) 
InBlock.gif
//                MainForm.conn.Open();
InBlock.gif
            string str_Conn="server=SERVER-DBT;database=LogERP;uid=logerp;pwd=logerpok;Max Pool Size=20000;";
InBlock.gif            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                SqlConnection sqlconn
=new SqlConnection(str_Conn);
InBlock.gif                sqlconn.Open();
InBlock.gif               
InBlock.gif                SqlCommand insert 
= new SqlCommand("Insert into ENTR_Image(EImage,VImage) values (@EImage,@VImage)");
InBlock.gif                insert.Connection
=sqlconn;
InBlock.gif                SqlParameter imageParameter 
= 
InBlock.gif                    insert.Parameters.Add(
"@EImage", SqlDbType.Binary);
InBlock.gif                imageParameter.Value 
= content;
InBlock.gif                imageParameter.Size  
= content.Length;
InBlock.gif
InBlock.gif                SqlParameter imageParameter1 
= 
InBlock.gif                    insert.Parameters.Add(
"@VImage", SqlDbType.Binary);
InBlock.gif                imageParameter1.Value 
= connect1;
InBlock.gif                imageParameter1.Size  
= connect1.Length;
InBlock.gif                
InBlock.gif
InBlock.gif                
int i=insert.ExecuteNonQuery();                
InBlock.gif                sqlconn.Close();
InBlock.gif                MessageBox.Show(i.ToString());
InBlock.gif
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                MessageBox.Show(ex.Message.ToString());
InBlock.gif                MessageBox.Show(ex.StackTrace.ToString ()); 
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
//                MainForm.conn.Close();
ExpandedSubBlockEnd.gif
            }

ExpandedBlockEnd.gif        }
 

新增以后根据Guid进行查询,图象
None.gif        private string str_Guid;
None.gif        
public string str_ImageGuid
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                str_Guid
=value;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

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

InBlock.gif                
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif
ExpandedSubBlockEnd.gif                }

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

InBlock.gif                
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
ExpandedSubBlockEnd.gif                }

InBlock.gif                sqlconn.Close();
InBlock.gif                
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                MessageBox.Show(ex.Message.ToString());
InBlock.gif                MessageBox.Show(ex.StackTrace.ToString ()); 
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
byte[] 的初始化:
ExpandedBlockStart.gifContractedBlock.gif  byte[] byt=dot.gif{};
None.gif            ClassEnt_rsDrawing.Browser
=byt;

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

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

None.gif
辅助代码:
保存对话框
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif        
/// 另存为 保存文件对话框
InBlock.gif        
/// </summary>
ExpandedBlockEnd.gif        
/// <returns></returns>

None.gif        private string fun_savefilename()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
string savefilename="";
InBlock.gif            SaveFileDialog saveFileDialog1 
= new SaveFileDialog(); 
InBlock.gif            saveFileDialog1.Filter 
= "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*"  ;
InBlock.gif            
InBlock.gif            saveFileDialog1.FilterIndex 
= 1 ;
InBlock.gif            saveFileDialog1.RestoreDirectory 
= true ;
InBlock.gif            
InBlock.gif            
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                savefilename
=saveFileDialog1.FileName;                 
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return savefilename;
ExpandedBlockEnd.gif        }

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

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

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

None.gif        public static byte[] GetByteImage(string str_Sql)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{            
InBlock.gif            
string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnStr"].ToString();
ExpandedSubBlockStart.gifContractedSubBlock.gif            
byte [] content=dot.gif{};
InBlock.gif            SqlConnection sqlconn
=new SqlConnection(connectionString);
InBlock.gif            sqlconn.Open();            
InBlock.gif            SqlCommand cmd
=new SqlCommand(str_Sql);
InBlock.gif            cmd.Connection
=sqlconn;
InBlock.gif            content 
= (byte[] )cmd.ExecuteScalar();
InBlock.gif            sqlconn.Close();
InBlock.gif            
return content;
ExpandedBlockEnd.gif        }

显示byte[] 到Form 里面
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif        
/// 显示图象到窗体
InBlock.gif        
/// </summary>
ExpandedBlockEnd.gif        
/// <param name="byt_Image"></param>

None.gif        private void ImageLoad(byte[] byt_Image)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            DevExpress.XtraEditors.PictureEdit pb 
= new DevExpress.XtraEditors.PictureEdit();
InBlock.gif            Form f
= new Form();
InBlock.gif            f.Controls.Add(pb);
InBlock.gif            f.MinimizeBox 
= false;
InBlock.gif            f.MaximizeBox
=false;
InBlock.gif            pb.Dock
=DockStyle.Fill;
InBlock.gif            pb.Properties.SizeMode 
= DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch ;
InBlock.gif            f.StartPosition 
= FormStartPosition.CenterScreen;
InBlock.gif            pb.Properties.PictureStoreMode 
= DevExpress.XtraEditors.Controls.PictureStoreMode.ByteArray;
InBlock.gif            pb.EditValue 
= byt_Image;
InBlock.gif            f.Show();
ExpandedBlockEnd.gif        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值