显示数据库中存储的图像
显示数据库中存储的图像
1、给解决方案添加一个新的Windows Forms应用程序项目DisplayDBImages。把Form1.cs更名为DisplayDBImages.cs
2、给窗体添加一个TextBox、一个Button和一个PictureBox
![](http://images0.cnblogs.com/blog/532489/201308/25235258-a9121509b4404bb588acb6904607085a.png)
3、给项目添加一个新类Images。代码如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
namespace DisplayDBImages
{
class Images
{
string strFileName = null;
byte[] imageBytes = null;
SqlConnection conn = null ;
SqlCommand cmd = null;
SqlDataReader reader = null ;
public Images()
{
string strConn = @"server=.\MSSQL2012;integrated security=true;initial catalog=tempdb;";
conn = new SqlConnection (strConn);
cmd = new SqlCommand( @"select imagefile, imagedata from imagetable", conn);
conn.Open();
reader = cmd.ExecuteReader();
}
public Bitmap GetImage()
{
MemoryStream ms = new MemoryStream (imageBytes);
Bitmap bmp = new Bitmap(ms);
return bmp;
}
public string GetFileName()
{
return strFileName;
}
// 读取一行记录
public bool GetRow()
{
if (reader.Read())
{
strFileName = ( string)reader.GetValue(0);
imageBytes = ( byte[])reader.GetValue(1);
return true;
}
else
{
return false;
}
}
public void EndImages()
{
reader.Close();
conn.Close();
}
}
}
4、把Images类型的实例变量添加到 DisplayDBImages.Designer.cs中
private System.Windows.Forms. TextBox textBox1;
private System.Windows.Forms. Button button1;
private System.Windows.Forms. PictureBox pictureBox1;
private Images images;
5、记得释放images实例对象。DisplayDBImages.Designer.cs中的DisplayDBImages的Dispose方法中,插入以下代码:
protected override void Dispose(bool disposing)
{
images.EndImages();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
6、最后,DisplayDBImages.cs的代码如下:
// DisplayDBImages.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DisplayDBImages
{
public partial class DisplayDBImages : Form
{
// 显示图片
private void ShowImages()
{
if (images.GetRow())
{
this.textBox1.Text = images.GetFileName();
this.pictureBox1.Image = ( Image)images.GetImage();
}
else
{
this.textBox1.Text = "完成" ;
this.pictureBox1.Image = null;
}
}
public DisplayDBImages()
{
InitializeComponent();
images = new Images();
ShowImages();
}
private void button1_Click( object sender, EventArgs e)
{
ShowImages();
}
}
}