我正在尝试创建一个函数,该函数允许我的应用向互联网URL上的图像分配image.Source
。在下载图像本身之前,我还需要下载BitmapFrame
以获得图像的尺寸详细信息。
问题是我的代码的bFrame.DownloadCompleted
部分没有用某些图像触发,所以我需要知道为什么下载事件没有一直触发,以及如何解决它适用于每张图像。
这是我的代码:
private static void GetWebImage(Image image, string path)
{
// Adjust image size to the source image's dimensions.
var bFrame = BitmapFrame.Create(new Uri(path), BitmapCreateOptions.None, BitmapCacheOption.None);
if (bFrame.IsDownloading)
{
bFrame.DownloadCompleted += (e, arg) =>
{
image.Width = bFrame.PixelWidth;
image.Height = bFrame.PixelHeight;
// Check whether the bitmap is in portrait orientation.
bool portrait = false;
if (image.Height > image.Width) { portrait = true; }
// Resize large images to the correct proportions.
double shrinkRatio = 0;
if (portrait && image.Height > 300)
{
shrinkRatio = 300 / image.Height;
image.Height = image.Height * shrinkRatio;
image.Width = image.Width * shrinkRatio;
}
else if (!portrait && image.Width > 400)
{
shrinkRatio = 400 / image.Width;
image.Height = image.Height * shrinkRatio;
image.Width = image.Width * shrinkRatio;
}
// Round the edges of the image.
image.Clip = new RectangleGeometry(new Rect(0, 0, image.Width, image.Height), 6, 6);
// Download the image from the URL.
BitmapImage bImage = new BitmapImage();
bImage.BeginInit();
bImage.UriSource = new Uri(path, UriKind.Absolute);
bImage.EndInit();
image.Source = bImage;
};
}
}
答案 0 :(得分:1)
不知道为什么BitmapFrame确实会那样。
但是,您可以将BitmapImage直接分配给image.Source
,以强制立即下载图像。
private static void GetWebImage(Image image, string path)
{
var bitmap = new BitmapImage(new Uri(path));
if (bitmap.IsDownloading)
{
bitmap.DownloadCompleted += (s, e) => AdjustSize(image, bitmap);
}
else
{
AdjustSize(image, bitmap);
}
image.Source = bitmap;
}
private static void AdjustSize(Image image, BitmapSource bitmap)
{
image.Width = bitmap.PixelWidth;
image.Height = bitmap.PixelHeight;
if (image.Height > image.Width)
{
if (image.Height > 300)
{
image.Width *= 300 / image.Height;
image.Height = 300;
}
}
else if (image.Width > 400)
{
image.Height *= 400 / image.Width;
image.Width = 400;
}
image.Clip = new RectangleGeometry(
new Rect(0, 0, image.Width, image.Height), 6, 6);
}