Display image from sql server using c#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I already stored the image in the SQL database. How do I retrieve it? Any
help is appreciated.
 
Hi Bama,

1) Retrieve the image from the database as a byte[].
2) Feed the byte[] to a MemoryStream
3) Create an Image using Image.FromStream
 
Thank you for your reply. I managed to display the image. Now I want to
restrict the image size and also the type. How do I do that?

It is an employee profile. I store the images for each of them. How do I
display a blank screen if dont have image for particular person.

Thanks...


--
-----r b a m a------


Morten Wennevik said:
Hi Bama,

1) Retrieve the image from the database as a byte[].
2) Feed the byte[] to a MemoryStream
3) Create an Image using Image.FromStream


I already stored the image in the SQL database. How do I retrieve it? Any
help is appreciated.
 
You can create a new Bitmap with the proper size and draw the original
image to the new Bitmap. The code below will compress (or expand) the
original image to 100x130 pixels

Image i = Image.FromFile(filename);

Bitmap bmp = new Bitmap(100, 130);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(i, 0, 0, 100, 130);
}

For blank images you need to check if there are no bytes in the image
field, or maybe check for DBNull.Value if the field is empty (null).

Instead of creating a new bitmap in the code above you can use a default
image for indicating no profile image is available, and, something like
this:

Bitmap bmp = (Bitmap)Bitmap.FromFile(defaultimage);

Image i = GetImageFromDatabase(employeeId);

if(i != null)
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(i, 0, 0, 100, 130);
}
}
 
Back
Top