2012-06-30 69 views
2

我需要將圖像發送到在PHP中實現的SOAP Web服務。將圖像從.Net客戶端發送到SOAP 1.0 webservice

該服務的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#應用​​程序中引用該服務用於Image01的數據類型爲String

如何從磁盤獲取圖像並以正確的方式發送編碼以通過此複雜類型發送它?

將不勝感激示例代碼。

回答

2

加載鏡像成一個byte[]類型,然後運行它通過一個Convert.ToBase64String()

有一個代碼on this question好的樣品從磁盤上的文件加載到一個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; 
} 

所以你只是做

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

並通過網絡服務調用回傳。我避免使用Image.FromFile調用,因此您可以將此示例與其他非圖像調用重新用於通過web服務發送二進制信息。但是,如果您只想使用圖像,請將此代碼塊替換爲Image.FromFile()命令。

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(); 
相關問題