Windows Phone实用开发技巧(39):WebBrowser引用独立存储空间中的图片

为了节省流量,我们在程序中可能需要将图片缓存到本地,在第二次显示的时候就可以直接从本地读取,而不需再次从网络下载。

特别是新闻一类的app,显示新闻内容的时候有时候会采用WebBrowser显示,那么如何让WebBrowser使用缓存的图片呢?有两种方法:

1. 使用图片的绝对路径,直接引用

2. 使用图片的相对路径,创建html文件显示

本文以一个简单demo的形式讲讲上述两种方法:

首先我们将项目中的一张图片copy至独立存储空间

private void SaveFilesToIsoStore()
{
    //These files must match what is included in the application package,
    //or BinaryStream.Dispose below will throw an exception.
    string[] files = { "1.jpg" };

    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

    if (false == isoStore.FileExists(files[0]))
    {
        foreach (string f in files)
        {
            StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
            using (BinaryReader br = new BinaryReader(sr.Stream))
            {
                byte[] data = br.ReadBytes((int)sr.Stream.Length);
                SaveToIsoStore(f, data);
            }
        }
    }
}

private void SaveToIsoStore(string fileName, byte[] data)
{
    string strBaseDir = string.Empty;
    string delimStr = "/";
    char[] delimiter = delimStr.ToCharArray();
    string[] dirsPath = fileName.Split(delimiter);

    //Get the IsoStore.
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

    //Re-create the directory structure.
    for (int i = 0; i < dirsPath.Length - 1; i++)
    {
        strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
        isoStore.CreateDirectory(strBaseDir);
    }

    //Remove the existing file.
    if (isoStore.FileExists(fileName))
    {
        isoStore.DeleteFile(fileName);
    }

    //Write the file.
    using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
    {
        bw.Write(data);
        bw.Close();
    }
}
方式一:使用绝对路径
private void DisplayUsingAbsolutePath()
{
    string appPath = string.Format("file:///Applications/Data/{0}/Data/IsolatedStore", "ac85cd27-463a-4258-9fd2-a45dba5beb0a");
    string imgPath = appPath + "/1.jpg";
    webBrowser1.NavigateToString("<html><img src='" + imgPath + "' width=100% /></html>");
}

其中{0}是应用程序的app id,我们拼凑html,img标签使用的src路径为图片的绝对路径

方式二:使用相对路径

private void AnotherWayToReferImageInIso()
{
    //create html
    string htmlPath = "index.htm";

    string html = "<html><img src='1.jpg' width=100% /></html>";

    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(htmlPath))
        {
            store.DeleteFile(htmlPath);
        }
        using (var stream = store.CreateFile(htmlPath))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(html);
            stream.Write(buffer, 0, buffer.Length);
        }
    }

    webBrowser1.Navigate(new Uri(htmlPath, UriKind.RelativeOrAbsolute));
}

创建html文件,html引用的图片路径为图片相对于html文件的路径,然后显示html文件即可

 

源代码可以在这里获取。

posted @ 2012-09-10 16:34  Alexis  阅读(3135)  评论(8编辑  收藏  举报