如何讓Restful Service回應圖片

在一般利用WCF還做restful的服務,回應的部分可以指定要輸出為XML格式或是JSON格式,那麼如果說想要直接回應一張圖片的時候應該要怎麼進行呢?

手上是用WPF的應用程式,先Self Host一個restful service上去,之後來處理回應圖片的部分,下面是參考資訊來源
Self host
http://stackoverflow.com/questions/20805317/how-to-set-up-wcf-self-hosted-rest-service

Response image
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/fetching-image-using-wcf-rest-service/
http://stackoverflow.com/questions/12781173/cant-return-image-from-wcf-rest-service

主要的方式便是將圖片轉換成Stream,之後http這邊設定回應的類型是image,這樣就可以達成想要的樣子了,下面來看看程式碼的部分吧

Interface
    [ServiceContract]
interface IMyService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/GetImage", Method = "GET",
        RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.Bare)]
    Stream GetImage();
}
很簡單的只有一個GetImage的Method

主程式這邊在Loaded事件中,去執行Self Host的相關動作
private void StartHost()
{
    Uri httpUrl = new Uri(string.Format(
        "http://{0}:{1}/",
        Properties.Settings.Default.HostName,
        Properties.Settings.Default.HostPort));
 
    var host = new WebServiceHost(typeof(MainWindow), httpUrl);
    var binding = new WebHttpBinding(); 
    host.AddServiceEndpoint(typeof(IMyService), binding, "");
    ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
    stp.HttpHelpPageEnabled = false;
 
    host.Open();
}

介面實作的部分會大概想是這樣子,這邊是複製整個畫面的目前樣子
private void GetImage()
{
    Bitmap b = new Bitmap(
        (int)System.Windows.SystemParameters.PrimaryScreenWidth,
        (int)System.Windows.SystemParameters.PrimaryScreenHeight);
    using (Graphics g = Graphics.FromImage(b))
    {
        System.Windows.Point pt = new System.Windows.Point(00);
        g.CopyFromScreen((int)pt.X, (int)pt.Y, 00, b.Size);
    }
    this.capturedImage = b;
}
 
        #region Service implement
 
Stream IMyService.GetImage()
{
    MemoryStream fs = new MemoryStream();
    this.GetImage();
    this.capturedImage.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
    fs.Position = 0;
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
    return fs;
}
 
        #endregion

要特別注意的地方是MemoryStream在Save之後,位置會跑到最後的地方;不改變Position的話,使用瀏覽器去察看回應的時候就只會看到一個『叉燒包』了,是不是很簡單呢?趕緊動手來玩玩看吧!

留言

這個網誌中的熱門文章

開啟cshtml檔案時,出現『並未將物件參考設定為物件執行個體』的錯誤訊息

無法設定中斷點 尚未載入符號檔

DataGridView欄位計算總合