如何从数据库显示图片?

时间:2011-06-26 16:34:07

标签: c# sql-server

我尝试在PictureBox的C#.Net Windows窗体中显示来自SQL Server 2008的图像。

我不知道如何从SQL Server检索图像,也不知道如何在PictureBox中显示。如果你好的话,请为我写一段代码......

感谢。

1 个答案:

答案 0 :(得分:4)

您尚未指定如何访问此数据库,因此我假设您使用的是普通的ADO.NET。在这种情况下,您可以使用一种方法来查询数据库并将图像作为字节数组返回:

public byte[] GetImageData(int imageId)
{
    using (var connection = new SqlConnection(SomeConnectionString))
    using (var command = connection.CreateCommand())
    {
        connection.Open();
        command.CommandText = "SELECT image_data FROM images WHERE image_id = @imageId";
        command.Parameters.AddWithValue("@imageId", imageId);
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                const int CHUNK_SIZE = 2 * 1024;
                byte[] buffer = new byte[CHUNK_SIZE];
                long bytesRead;
                long fieldOffset = 0;
                using (var stream = new MemoryStream())
                {
                    while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
                    {
                        stream.Write(buffer, 0, (int)bytesRead);
                        fieldOffset += bytesRead;
                    }
                    return stream.ToArray();
                }
            }
        }
    }
    throw new Exception("An image with id=" + imageId + " was not found");
}

然后将其加载到图片框中:

private void Form1_Load(object sender, EventArgs e)
{
    var pb = new PictureBox();
    using (var stream = new MemoryStream(GetImageData(1)))
    {
        pb.Image = Image.FromStream(stream);
    }
    Controls.Add(pb);
}