2

I need to send an image to a SOAP web service implemented in PHP.

The WSDL for the service looks like this...

<xsd:complexType name="Product">
  <xsd:all>
    <xsd:element name="ProductId" type="xsd:int"/>   
    <xsd:element name="Image01" type="xsd:base64Array"/>
  </xsd:all>
</xsd:complexType>

When I reference this service in my C# application the data type used for Image01 is String.

How can I get an image from disk and send encode it in the correct way to send it via this complex type?

Would appreciate sample code.

Remotec
  • 10,304
  • 25
  • 105
  • 147

2 Answers2

2

You can use this code to load the Image, transform to Byte[] and convert to Base64

Image myImage = Image.FromFile("myimage.bmp");
MemoryStream stream = new MemoryStream();
myImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageByte = stream.ToArray();
string imageBase64 = Convert.ToBase64String(imageByte);
stream.Dispose();
myImage.Dispose();
Hyralex
  • 990
  • 1
  • 8
  • 25
2

Load the image up into a byte[] type then run it through a Convert.ToBase64String()

There's a nice sample of code on this question to load a file from disk into a byte[]

public byte[] StreamToByteArray(string fileName)
{
byte[] total_stream = new byte[0];
using (Stream input = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
    byte[] stream_array = new byte[0];
    // Setup whatever read size you want (small here for testing)
    byte[] buffer = new byte[32];// * 1024];
    int read = 0;

    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        stream_array = new byte[total_stream.Length + read];
        total_stream.CopyTo(stream_array, 0);
        Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
        total_stream = stream_array;
    }
}
return total_stream;
}

So you'd just do

Convert.ToBase64String(this.StreamToByteArray("Filename"));

And pass that back via the web service call. I've avoided using the Image.FromFile call so you can re-use this example with other non image calls to send binary information over a webservice. But if you wish to only ever use an Image then substitute this block of code for an Image.FromFile() command.

Community
  • 1
  • 1
John Mitchell
  • 9,653
  • 9
  • 57
  • 91