在Webbrowser控件中使用本地图像

我在我的Wp7应用程序中使用Web浏览器控件,但我似乎无法在Web浏览器中放置App目录中的图像。

我将一些图像放在与.cs和.xaml文件相同的目录中的文件夹中。 现在我尝试将它们放在webbrowser控件中,但我似乎无法让它工作。

  

上面两个显然不起作用,我的猜测应该是这样的:

  

“SilverlightApplication”和“组件”应该被其他东西取代,但我不知道:(

您需要将图像存储在隔离存储中,然后从那里显示图像。 我已经整理了一个样本,您可以从以下位置下载: –

http://www.smartmobiledevice.co.uk/projects/webbrowserimagesample.zip

这基于MSDN文章如何:使用Windows Phone的WebBrowser控件显示静态Web内容 。

在Windows Phone 8上,某些WinRT类可用,可以获取应用程序隔离存储的文件系统路径。 因此,IsoStorage中文件的绝对URL将是:

 string URL = "file://" + Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\folder\\filename.png"; 

WebBrowser控件在NavigateToString()和HTML中使用这些URL。 或者,您可以将IsoStorage指定为基础并始终使用相对URL。 isostore:url不起作用,我试过了。 ms-appx://local/

为了完整起见,您可以非常类似地获取应用程序资源的文件系统路径。 那就是Windows.ApplicationModel.Package.Current.InstalledLocation.Path

你可以通过连接上面给出的动态图像保存示例应用程序动态更新数组,

 string[] files = { "readme.htm", "desert.jpg", "sample.jpg" }; 

在写入隔离之前,您可以删除现有的

  private void SaveFilesToIsoStore() { //These files must match what is included in the application package, //or BinaryStream.Dispose below will throw an exception. string[] files = { "readme.htm", "desert.jpg", "sample.jpg" }; IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication(); if(isoStore.FileExists(files[0])) { isoStore.DeleteFile(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(); } } 

这是一个非常古老的主题,但我已经提出了一个解决方案,因为我们今天刚刚更新了一个WP7应用程序。

秘诀是首先将图像转换为基本64表示,所以从这段代码开始:

  private string GetBase64(string f) { string ret = ""; { StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative)); using (BinaryReader br = new BinaryReader(sr.Stream)) { byte[] data = br.ReadBytes((int)sr.Stream.Length); ret = System.Convert.ToBase64String(data); } } return ret; } 

现在,你想将图像注入代码(我的是GIF),使用它

 StringBuilder sb = ... // a string builder holding your webpage String b64 = GetBase64("assets/images/filename.gif"); sb.AppendFormat(@"", b64);