Andrew Maddison

Flowerchild.

Base 64 Encoding an Image to Pass Across a Web Service

I’m writing a little app which will need to submit (amongst other things) an image to a server. The server exposes web services (SOAP for the moment), and because I couldn’t think of any other way to pass a whole image file in, I tried base 64 encoding it, as it turns out it was really simple to get an example working.

In the source application, I simply loaded the image as a byte array, and encoded it.

byte[] imageBytes = File.ReadAllBytes(@"c:\someExistingImage.jpg");
string b64image = Convert.ToBase64String(imageBytes, Base64FormattingOptions.None);

Then I simply passed that string as an argument on a method in my web service. At the other end I was able to do the revese with equally little fuss:

[WebMethod]
public void SubmitImage(string base64EncodedImage)
{
    byte[] rawImage = Convert.FromBase64String(base64EncodedImage);
    File.WriteAllBytes(@"c:\someNewFilename.jpg", rawImage);
}

Worked first time! On the real thing the image is actually going to be stored in a DB in the short term, and only retrieved later, but this proved that the base 64 bit worked.

I assume that there might be a better way of solving this problem (submitting an image to a remote server from code), possibly by using http post, but this seemed easier.

Comments