Reputation: 29
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.
Upvotes: 0
Views: 1875
Reputation: 1038710
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);
}
Upvotes: 4