簡體   English   中英

在WinRT WebView控件中顯示圖像

[英]Display an image in WinRT WebView control

假設我的頁面中有一個WebView ,其內容由WebView.NavigateToString(string html)加載。 現在的問題是html字符串包含一些<img>標記,例如

<img src="http://www.remotefakesite.com/1.jpg" />

但是,除非請求具有特殊的cookie,否則無法正確下載圖像。 但是請求是由控件發送的,我不知道如何修改請求(向其中添加cookie)。 我嘗試設置HttpRequest.DefaultWebProxy ,但不適用於內置控件發送的請求。

一種替代解決方案是通過我自己的HttpWebRequest(具有正確的cookie)將圖像下載到本地文件夾,然后將html字符串中的img標簽修改為

<img src="files:///xxxxx" />

但顯然files:///方案違反了Metro應用程序的安全策略。 ms-appxms-appdata都不起作用,因為下載的圖像不屬於我的項目。

你有什么解決辦法嗎?

我在這里做了一些測試,是否可以將圖像下載到項目文件夾中的示例中。 在“媒體”文件夾中的示例,則可以使用以下代碼打開圖像:

<img src="ms-appx-web:///Media/10.jpg" />

如果圖像大小沒有問題,則可以嘗試使用帶有必需cookie的自定義HTTP請求下載圖像,對它進行base64編碼,然后將其插入src屬性:

<img src="data:image/png;base64,iVBOR8Q..." />

並使用NavigateToString方法將其與其他html一起傳遞給WebView。

這可能不是世界上最好的解決方案,但與其他選項相比,它只是可行。

您可以啟用應用程序的圖片庫功能,並使用圖片庫位置下載圖像。 這是有關訪問圖片庫的指南

更新:

然后從圖片庫中的圖像對象創建圖像。 一個例子是:

async private void LoadImage()
{
    try
    {
        IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary =
            await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
        MessageBlock.Text += "Show image: " + resultsLibrary[0].Name + "\n";
        Windows.Storage.Streams.IRandomAccessStream imageStream =
            await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
        Windows.UI.Xaml.Media.Imaging.BitmapImage imageBitmap =
            new Windows.UI.Xaml.Media.Imaging.BitmapImage();
        imageBitmap.SetSource(imageStream);
        ImagePlayer.Source = imageBitmap;
    }
    catch (Exception ex)
    {
        MessageBlock.Text += "Exception encountered: " + ex.Message + "\n";
    }
}

您可以更好地使用它,就像編寫HTML一樣:

this.InitializeComponent();

string htmContent = @" <html>
<head></head>
<body>
<img src="http://www.remotefakesite.com/1.jpg" />
</body>
</html>";

preview.NavigateToString(htmContent);

僅您需要一個webview元素(此處稱為“預覽”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM