开发者

How to show picture from database?

I trying to show images from SQL Server 2008 in a PictureBox开发者_开发知识库 of C#.Net Windows Form.

I don't know how to retrieve images from SQL Server and don't know how to show in the PictureBox. Please write a code segment for me if you Okay...

Thanks.


You haven't specified how are you accessing this database, so I assume you are using plain ADO.NET. In this case you could have a method which would query your database and return the image as a byte array:

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");
}

and then load it into a picture box:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜