Live Chat Icon For mobile
Live Chat Icon

How can I display image from a Sql Server database

Platform: ASP.NET| Category: GDI+

VB.NET

 ’Function
Public Function showImage(empid As Int32) As Byte()
   Dim myconnection As New SqlConnection('Server=localhost;uid=sa;password=;database=northwind;')
   Dim mycommand As New SqlCommand('Select Employeeid, FirstName,Photo from Employees where employeeid =' + empid.ToString(), myconnection)
   myconnection.Open()
   Dim dr As SqlDataReader = mycommand.ExecuteReader()
   dr.Read()
   Dim imgbyte As Byte() = CType(dr('Photo'), Byte())
   Return imgbyte
End Function ’showImage 

’In Page_Load
Dim data As Byte() = showImage(2)
Dim offset As Int32 = 78
Dim mstream As New System.IO.MemoryStream()
mstream.Write(data,offset,data.Length -offset)
Dim bmp As New System.Drawing.Bitmap(mstream)
bmp.Save(Server.MapPath('sample.jpeg'), System.Drawing.Imaging.ImageFormat.Jpeg)
mstream.Close()
Image1.ImageUrl = Server.MapPath('sample.jpeg')

C#

//Function
public byte []  showImage(Int32 empid)  
{
	SqlConnection  myconnection  = new SqlConnection ('Server=localhost;uid=sa;password=;database=northwind;');
	SqlCommand mycommand = new SqlCommand ('Select Employeeid, FirstName,Photo from Employees where employeeid =' + empid, myconnection);
	myconnection.Open ();
	SqlDataReader  dr= mycommand.ExecuteReader();
	dr.Read();
	byte[]  imgbyte =(byte[]) dr['Photo']; 
	return imgbyte;
		
}
//In Page_Load
byte[] data  = showImage (2);
Int32  offset  =78;
System.IO.MemoryStream mstream = new System.IO.MemoryStream  ();
mstream.Write(data, offset, data.Length - offset);
System.Drawing.Bitmap bmp= new System.Drawing.Bitmap(mstream);
bmp.Save(Server.MapPath ('sample.jpeg'), System.Drawing.Imaging.ImageFormat.Jpeg );
mstream.Close();
Image1.ImageUrl = Server.MapPath('sample.jpeg');

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.