这张图片“存在于哪里?”是否可以在本地文件系统或网络上访问?如果是这样,我建议您的 WebService 接受 URI(可以是 URL 或本地文件)并将其作为 Stream 打开,然后使用 StreamReader 读取其内容。
示例(但将异常包装在FaultExceptions中,并添加FaultContractAttributes):
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
[OperationContract]
public void FetchImage(Uri url)
{
// Validate url
if (url == null)
{
throw new ArgumentNullException(url);
}
// If the service doesn't know how to resolve relative URI paths
/*if (!uri.IsAbsoluteUri)
{
throw new ArgumentException("Must be absolute.", url);
}*/
// Download and load the image
Image image = new Func<Bitmap>(() =>
{
try
{
using (WebClient downloader = new WebClient())
{
return new Bitmap(downloader.OpenRead(url));
}
}
catch (ArgumentException exception)
{
throw new ResourceNotImageException(url, exception);
}
catch (WebException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
// IOException and SocketException are not wrapped by WebException :(
catch (IOException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
catch (SocketException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
})();
// Do something with image
}