Transporting Pictures over ASP.NET Web Services

So you can send a lot of stuff over web services, mostly primitive types, but what if you want to send pictures?

I’m not talking about sending the URL to a picture, but sending the actual image data over a web service, so that the client can display it. It’s really very simple, but also a fun addition. On the Web Service side, you need to take the image and encode it into a primitive type that can be handled through SOAP. To do this, I load the image, then convert its contents into a Base64 encoded string. I can then send this string back to the client.

Example:

[WebMethod]
public string GetPicture() { 
  // Load the picture 
  Image img = Image.FromFile("Path/To/Picture.jpg"); 
  // Create a memory stream, and put the image contents into it. 
  MemoryStream stream = new MemoryStream(); 
  img.Save(stream, img.RawFormat); 
  // return data, encoded in Base64 
  return Convert.ToBase64String(stream.ToArray()); 
}

Very simple! Now on the client side, we simply reverse the process.

Here is a synchronous example, for a better asynchronous example, have a look at my Visual Studio solution. This example is for a Windows form application, with a PictureBox object.

private void LoadImage() { 
  // Create web service 
  WebServiceSoapClient service = new WebServiceSoapClient(); 
  // Fetch encoded image using the web service method 
  string encodedImage = service.GetPicture(); 
  // turn the Base64 string back into bytes 
  byte[] buffer = Convert.FromBase64String(encodedImage); 
  // create a stream from the data 
  MemoryStream stream = new MemoryStream(buffer, false); 
  // recreate Image object, and display it in pictureBox1 
  Image img = Image.FromStream(stream); 
  pictureBox1.Image = img; 
} 

If you encounter errors, regarding the max length of strings, simply update the properties: maxBufferSize maxRecievedMessageSize and maxStringContentLength in the app.config file, and set the value to which 2048000 should be big enough!

You can download a solution folder, with a fully working example here: http://www.jak.cx/downloads/PicturesOverWebServiceTest.zip