2

我需要将图像发送到用 PHP 实现的 SOAP Web 服务。

服务的 WSDL 如下所示...

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

当我在 C# 应用程序中引用此服务时,用于的数据类型Image01String.

如何从磁盘获取图像并以正确的方式对其进行编码以通过这种复杂类型发送它?

将不胜感激示例代码。

4

2 回答 2

2

您可以使用此代码加载图像,转换为 Byte[] 并转换为 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();
于 2012-06-30T10:05:56.273 回答
2

将图像加载到byte[]类型中,然后通过Convert.ToBase64String()

这个问题有一个很好的代码示例,可以将文件从磁盘加载到字节[]

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;
}

所以你就这样做

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.

于 2012-06-30T10:13:15.317 回答