本教程提供了一个详细的步骤说明和代码示例,展示如何在C#编程语言环境中实现图片到二进制数据以及反向转换的过程。
本段落主要介绍了如何使用C#实现图片与二进制数据之间的转换,并展示了在数据库中存储这些图像的具体方法。
一、将图片转为二进制
为了把一张图片转换成二进制格式,可以利用FileStream和BinaryReader类来读取文件内容并将其转化为字节数组。以下是一个示例代码:
```csharp
private byte[] SaveImage(String path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length);
return imgBytesIn;
}
```
二、将二进制转为图片
反过来,如果需要把一个字节数组转换回图像格式的话,则可以使用MemoryStream和Image.FromStream方法。下面的代码展示了具体的实现方式:
```csharp
public void ShowImgByByte(byte[] imgBytesIn)
{
MemoryStream ms = new MemoryStream(imgBytesIn);
pictureBox1.Image = Image.FromStream(ms);
}
```
三、将图片保存到数据库
在C#中,可以使用ADO.NET框架来处理与SQL Server之间的交互。以下代码展示了如何利用这种方法把图像数据存储进数据库:
```csharp
public void SaveImage(string MID, OpenFileDialog openF)
{
string strimg = openF.FileName.ToString();
FileStream fs = new FileStream(strimg, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length);
getcon(); // 假设此函数用于建立数据库连接
StringBuilder strSql = new StringBuilder();
strSql.Append(update S_jiben Set xs_photo=@Photo where S_num= + MID);
SqlCommand cmd = new SqlCommand(strSql.ToString(), link);
cmd.Parameters.Add(@Photo, SqlDbType.Binary).Value = imgBytesIn;
cmd.ExecuteNonQuery(); // 执行更新语句,将图片数据保存到数据库
}
```
四、从数据库读取图片
最后一种情况是从数据库中检索图像。同样地,可以使用ADO.NET来完成这项任务,并通过MemoryStream和Bitmap类把二进制流还原为图像对象:
```csharp
public void get_photo(string xs_ID, PictureBox ph)
{
byte[] imagebytes = null;
getcon(); // 假设此函数用于建立数据库连接
SqlCommand con = new SqlCommand(select * from S_jiben where S_num= + xs_ID , link);
SqlDataReader dr = con.ExecuteReader();
while (dr.Read())
{
imagebytes =(byte[])dr.GetValue(18); // 获取图像数据
}
dr.Close();
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
ph.Image = bmpt; // 将图片显示在PictureBox控件中
}
```
通过以上步骤,读者可以掌握如何使用C#进行文件与数据库之间的数据交互。