c#winform从数据库中提取二进制,转换成图片显示在pictureBox中
时间: 2024-10-23 08:13:14 浏览: 94
在C# WinForm中,你需要从数据库中获取已经存储为二进制的数据,然后将其转换为图片并在PictureBox中显示。以下是基本的步骤:
1. **数据库查询**:
使用`SqlDataReader`从数据库中读取包含图片数据的记录。假设你有一个字段名为`ImageData`,它存储的是二进制数据:
```csharp
string connectionString = "your_connection_string";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT ImageData FROM YourTable WHERE Id = @Id", connection);
command.Parameters.AddWithValue("@Id", yourImageId);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
byte[] imageData = (byte[])reader["ImageData"];
}
}
```
2. **图片解码**:
将二进制数组转换回图片对象,通常是通过`System.Drawing.Image.FromStream`或`System.Drawing.Image.FromMemoryStream`:
```csharp
MemoryStream ms = new MemoryStream(imageData);
Image image = Image.FromStream(ms);
```
3. **设置PictureBox**:
现在你可以把图片赋值给PictureBox的`Image`属性:
```csharp
pictureBox.Image = image;
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; // 或者根据需要调整缩放模式
```
4. **关闭流和读者**:
完成操作后,别忘了关闭`MemoryStream`和`SqlDataReader`:
```csharp
ms.Close();
reader.Close();
```
阅读全文
相关推荐

















