...A sample code to create webservice to retrieve image from database

- The Webservice uses DataReader to read the data from the database table and returns byte array.
- The client retrieves the data in form of byte array and saves it in the file with specified format .
- The client code uses System.IO.MemoryStream , System.Drawing.Bitmap and System.Drawing.Imaging.ImageFormat namespace to save the image.

[bold]Step 1: WebService (WSIMGjpeg.asmx)[/bold]

public byte [] showImage(Int32 empid)


SqlConnection myconnection = new SqlConnection ("Server=localhost;uid=sa;password=;database=north wind;");

SqlCommand mycommand = new SqlCommand ("Select Employeeid, FirstName,Photo from Employees where employeeid =" + empid, myconnection);

myconnection.Open ();

SqlDataReader dr= mycommand.ExecuteReader();


byte[] imgbyte =(byte[]) dr["Photo"];

return imgbyte;


[bold]Step 2: Client[/bold]

private void Page_Load(object sender, System.EventArgs e)


// Put user code to initialize the page here

localhost.WSIMGjpeg obj= new localhost.WSIMGjpeg();

byte[] data = obj.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 ("empimg.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg );


// Drag and drop <asp:image> tag on webform

Image1.ImageUrl = Server.MapPath("empimg.jpeg");


Read Complete Articles