HOW TO:在 Visual C# 中直接将一个图片从数据库复制到 PictureBox 控件


示例

  1. 使用以下结构创建一个 SQL Server 或 Access 表:
    CREATE TABLE BLOBTest
    (
    BLOBID INT IDENTITY NOT NULL,
    BLOBData IMAGE NOT NULL
    )
    					
  2. 打开 Visual Studio .NET,然后新建一个 Visual C# Windows 应用程序项目。
  3. 从工具箱向默认的 Form1 添加一个 PictureBox 和两个 Button 控件。将 Button1 的 Text 属性设置为 File to Database,并将 Button2 的 Text 属性设置为 Database to PictureBox
  4. 在窗体的代码模块顶部插入 using 语句:
    using System.Data.SqlClient;
    using System.IO;
    using System.Drawing.Imaging;
    					
  5. 将以下数据库连接字符串的声明添加到 public class Form1 :System.Windows.Forms.Form 类声明中,并根据需要调整连接字符串:
        String strCn = "Data Source=localhost;integrated security=sspi;initial catalog=mydata";
    					
  6. 将下面的代码插入 Button1 (File to Database) 的 Click 事件过程中。根据需要调整到一个可用示例图像文件的可用路径。此代码可将图像文件从磁盘(使用一个 FileStream 对象)读入 Byte 数组,然后使用一个参数化的 Command 对象将数据插入数据库。
    try
    {
    	SqlConnection cn = new SqlConnection(strCn);
    	SqlCommand cmd =  new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", cn);
    	String strBLOBFilePath = @"C:\blue hills.jpg";//Modify this path as needed.
    
    	//Read jpg into file stream, and from there into Byte array.
    	FileStream fsBLOBFile =  new FileStream(strBLOBFilePath,FileMode.Open, FileAccess.Read);
    	Byte[] bytBLOBData = new Byte[fsBLOBFile.Length]; 
    	fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
    	fsBLOBFile.Close();
    
    	//Create parameter for insert command and add to SqlCommand object.
    	SqlParameter prm = new  SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, bytBLOBData);
    	cmd.Parameters.Add(prm);
    
    	//Open connection, execute query, and close connection.
    	cn.Open();
    	cmd.ExecuteNonQuery();
    	cn.Close();
    }catch(Exception ex)
    {MessageBox.Show(ex.Message);}
    					
  7. 将下面的代码插入 Button2 (Database to PictureBox) 的 Click 事件过程。此代码将行从数据库中的 BLOBTest 表检索到一个数据集,复制最新添加的图像到 Byte 数组,然后到 MemoryStream 对象,接着将 MemoryStream 加载到PictureBox 控件的 Image 属性。
    try
    {
    	SqlConnection cn = new SqlConnection(strCn);
    	cn.Open();
    
    	//Retrieve BLOB from database into DataSet.
    	SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);	
    	SqlDataAdapter da = new SqlDataAdapter(cmd);
    	DataSet ds = new DataSet();
    	da.Fill(ds, "BLOBTest");
    	int c = ds.Tables["BLOBTest"].Rows.Count;
    
    	if(c>0)
    	{   //BLOB is read into Byte array, then used to construct MemoryStream,
    		//then passed to PictureBox.
    		Byte[] byteBLOBData =  new Byte[0];
    		byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
    		MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
    		pictureBox1.Image= Image.FromStream(stmBLOBData);
    	} 
    	cn.Close();
    }
    catch(Exception ex)
    {MessageBox.Show(ex.Message);}
    					
  8. 按 F5 键编译并运行该项目。
  9. 单击 File to Database 按钮将至少一个示例图像加载到数据库。
  10. 单击 Database to PictureBox 按钮将保存的图像显示在 PictureBox 控件中。
  11. 如果想能够直接将图像从 PictureBox 控件插入数据库,则请添加第三个 Button 控件,并将下面的代码插入其 Click 事件过程。此代码将图像数据从 PictureBox 控件检索到 MemoryStream 对象,将 MemoryStream 复制到一个 Byte 数组,然后使用一个参数化的 Command 对象将 Byte 数组保存到数据库。
    try
    {
    	SqlConnection cn = new SqlConnection(strCn);
    	SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", cn);
    
    	//Save image from PictureBox into MemoryStream object.
    	MemoryStream ms  = new MemoryStream();
    	pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
    
    	//Read from MemoryStream into Byte array.
    	Byte[] bytBLOBData = new Byte[ms.Length];
    	ms.Position = 0;
    	ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));
    
    	//Create parameter for insert statement that contains image.
    	SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false, 
    					0, 0,null, DataRowVersion.Current, bytBLOBData);
    	cmd.Parameters.Add(prm);
    	cn.Open();
    	cmd.ExecuteNonQuery();
    	cn.Close();
    }catch(Exception  ex)
     {MessageBox.Show(ex.Message);}
    					
  12. 运行该项目。单击 Database to PictureBox 按钮以显示刚才在 PictureBox 控件中保存过的图像。单击新添加的按钮将此图像从 PictureBox 保存到数据库。然后再次单击 Database to PictureBox 按钮以确认图像已正确保存。


http://support.microsoft.com/kb/317701/zh-cn


文中讲得十分的详细。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值