Silverlight中通過呼叫WebService來顯示資料庫中以流形式儲存的圖片

暖楓無敵發表於2011-10-13

在Web開發中,常見的做法如下:

將資料庫中讀取出來的內容以位元組陣列的形式儲存,字串型轉位元組陣列的方法是Convert.FromBase64String,然後以二進位制寫的方法將圖片資訊寫在頁面中。主要程式碼如下:


SWDM dm = new SWDM();
protected void Page_Load(object sender, EventArgs e)
{
    string strSQL = "select picContent from tb_ssxq where OBJECTID=1";
    DataSet ds = dm.getsql(strSQL);
    byte[] byteFileStream = Convert.FromBase64String(ds.Tables[0].Rows[0]["picContent"].ToString());
    Response.BinaryWrite(byteFileStream);
    Response.End();
}


在Silverlight中如何實現呢,其實差不多,只不過在WebService中的方法的返回值要是byte[]型別,然後在Silverlight中利用MemoryStream來接收並儲存圖片流資訊,然後將其作為BitmapImage的Source即可,最後利用Silverlight的Image控制元件即可顯示出該圖片。

WebService中的程式碼如下:

     /// <summary>
    /// 根據險情ID獲取實時險情的圖片資訊
    /// </summary>
    /// <param name="paramCity"></param>
    /// <returns></returns>
    [WebMethod(Description = "獲取某一個實時險情的圖片資訊")]
    public byte[] getSSXPictureQByID(string xqid)
    {
        byte[] byteFileStream = null;
        string strSQL = "select picContent  from tb_ssxq where OBJECTID=" + int.Parse(xqid);
        DataSet ds = dm2.getsql(strSQL);
        byteFileStream = Convert.FromBase64String(ds.Tables[0].Rows[0]["picContent"].ToString());
        return byteFileStream;
    }

Silverlight中程式碼:

<Grid x:Name="LayoutRoot" Background="White">
   <Border BorderBrush="#FF5BB0FF" BorderThickness="1" Margin="0">
         <Image x:Name="Image1" Margin="0" Stretch="None"/>
   </Border>
</Grid>


private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
        //獲取險情圖片資訊
        getPictureInfoSoapClient client = new getPictureInfoSoapClient();

        client.getSSXPictureQByIDCompleted += new EventHandler<getSSXPictureQByIDCompletedEventArgs>(client_getSSXPictureQByIDCompleted);
        client.getSSXPictureQByIDAsync(id);
}

//險情圖片
void client_getSSXPictureQByIDCompleted(object sender, getSSXPictureQByIDCompletedEventArgs e)
{
        MemoryStream ms = new MemoryStream(e.Result);
        BitmapImage image = new BitmapImage();
        image.SetSource(ms);
        this.Image1.Source = image;
}





相關文章