Windows应用商店加载URL图像并获取大小

时间:2014-03-10 05:00:24

标签: windows dimensions bitmapimage

我需要在C#Windows Store(Windows RT)应用程序中将8个图像加载到Image或BitmapImage元素中,并且需要找到它们的尺寸(甚至在它们显示之前)。我可以下载图像,但无法弄清楚如何获得大小(大小始终为零)。大小为零的原因是位图图像没有加载,但无法弄清楚如何等待图像加载,捕获指示图像已加载的函数。

以下是关键代码,ImageOpenedImageFailed永远不会被调用:

bm.ImageOpened += bm_ImageOpened;
bm.ImageFailed += bm_ImageFailed;
bm = new BitmapImage(new Uri(arbitraryImageUriThatKeepsChanging, UriKind.Absolute));
image.ImageFailed += image_ImageFailed;
image.ImageOpened += image_ImageOpened;
image.Source = new BitmapImage(new Uri(arbitraryImageUriThatKeepsChanging, 
               UriKind.Absolute)); 
/* .. at this point the image still has not been loaded,
 so can't find the dimensions or if it failed or not, and the functions to catch
 image opened and failed are never called..*/

我需要的只是从外部网站加载图像,并在显示图像之前找到尺寸。

1 个答案:

答案 0 :(得分:0)

你可以使用一个不可见的虚拟 - Image元素来预加载图像。

在您的Xaml中:

<Image Name="DummyImage" Visibility="Collapsed"/>

代码背后:

BitmapImage btm = new BitmapImage(new Uri("http://anyurl.com/foo.jpg"));
btm.DownloadProgress += btm_DownloadProgress;
DummyImage.Source = btm;

private void btm_DownloadProgress(object sender, DownloadProgressEventArgs e)
    {
        if (e.Progress == 100)
        {
            int width = ((BitmapImage)sender).PixelWidth;
        }
    }

您应该可以使用DownloadProgress或ImageLoaded事件。