zoukankan      html  css  js  c++  java
  • silverlight学习之获取照片的路径

    有时候我们要在逻辑代码里面动态的改变某张图片,可以通过改变图片的来源达到(就是改变Image控件的source)。

    1、从服务器端获取路径

    加入有个silverlight项目,在服务器端有个Images文件夹(在**.web 项目的根目录下),里面放着一些图片,客户端要通过wcf从服务器端获取这些照片(其实这里是获取路径,或者说链接),获取这些照片路径的代码如下:

    先获取服务器名称,再获取端口号(可能没有),最后获取应用程序的名称,这三个名称组成了基本路径。要精确定位到某张图片,还要加上图片所在的文件夹(一般放在silverlight解决方案的 .web项目的根目录下)——这里是image ,在加上图片的名字,再加上后缀名

     1         [OperationContract]
    2 public string GetPhotosPath(string name, out string picturePath)
    3 {
    4 //图片路径。images是 .web项目下放图片的文件夹。name是要查找照片的名字
    5 picturePath = GetBaseDirectory() + "images/"+ name + ".jpg";
    6 return picturePath;
    7 }
    8
    9 private string GetBaseDirectory()
    10 {
    11 // 服务器名称
    12 string serverName = HttpContext.Current.Request.ServerVariables["Server_Name"];
    13
    14 //端口号
    15 string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
    16
    17 // 应用服务名称
    18 string applicationName = HttpContext.Current.Request.ApplicationPath;
    19
    20 string path = "http://" + serverName + (port.Length > 0 ? ":" + port : string.Empty) + applicationName;
    21 return path;
    22 }

     2、在客户端改变照片源

    代码如下,e.Result是返回的照片路径。

    有时候不需要从服务器端获取,可以直接从客户端获取另一张图片,获取路径方法:"Image/" + name + ".jpg" ,

    假设 照片放在客户端项目的image(在客户端项目的根目录下)文件夹里, 后缀名可以是其他格式,name表示照片名字。


    客户端访问代码如下:

     1         void client_GetPhotosPathCompleted(object sender, ServiceRefEmpInfo.GetPhotosPathCompletedEventArgs e)
    2 {
    3 string imageURL = e.Result;
    4
    5 //如果返回的照片路径有误,则显示出错提示
    6 if (string.IsNullOrEmpty(imageURL))
    7 {
    8 imageURL = @"Images/falsePhotos.jpg";// 相对路径格式
    9
    10 }
    11
    12 Uri uri = new Uri(imageURL, UriKind.RelativeOrAbsolute);
    13 BitmapImage image = new BitmapImage(uri);
    14 ((MainPage)App.Current.RootVisual).imageEmp.Source = image;
    15
    16 // ((MainPage)App.Current.RootVisual).imageEmp.Source = new BitmapImage(new Uri(imageURL, UriKind.RelativeOrAbsolute));
    17
    18 }

    获取到照片的路径了,如何改变照片源呢?

    1、新建一个 Uri 对象 :Uri uri = new Uri(imageURL, UriKind.RelativeOrAbsolute);

    imageURL是照片的路径,UriKind.RelativeOrAbsolute表示imageURL是绝对路径还是相对路径。

    如果是 new Uri(imageURL) 则表示imageURL是以绝对路径

    2、用刚才新建的Uri对象的实例作为参数建立一个BitmapImage 对象:BitmapImage image = new BitmapImage(uri);

    3、把新的BitmapImage 实例作为照片源赋给 Image :
    ((MainPage)App.Current.RootVisual).imageEmp.Source = image;

     ((MainPage)App.Current.RootVisual).imageEmp表示Image控件的名字

  • 相关阅读:
    bug终结者 团队作业第二周
    dropdownlist绑定数据
    virtual与vmware
    后台控制输出table(有数据库)
    label 绑定数据
    flash不能显示中文
    dataset 多表查询
    MVC3 Razor视图引擎基础语法 [转]
    CreateAlias()与setFetchMode() [转 李丽芬]
    Linq Like [转 韩天伟]
  • 原文地址:https://www.cnblogs.com/zouzf/p/2400061.html
Copyright © 2011-2022 走看看