5

我的项目资产文件夹中有很多图像,我需要在应用程序启动时将它们加载到内存中。减少 CPU 负载和时间的最佳方法是什么。

我正在这样做:

for (int i = 0; i < 10; i++)
        {
            var smallBitmapImage = new BitmapImage
            {
                UriSource = new Uri(string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i), UriKind.Absolute)
            };

            theme.SmallDigits.Add(new ThemeDigit<BitmapImage> { Value = i, BitmapImage = smallBitmapImage, Image = string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i) });
        }

然后我将此 BitmapImage 绑定到图像控件。

但我不确定设置 UriSource 是否真的将图像加载到内存中。

我还看到了 BitmapImage 的 SetSourceAsync 属性。但我不确定如何在我的上下文中使用它。任何人都可以帮助我使用 SetSourceAsync 属性或加载图像的最佳方式....

谢谢

4

2 回答 2

1

因为我不想显示错误的答案,所以我必须在 10 秒后添加另一个答案......

例子:

BitmapImage image1 = LoadImageToMemory("C:\\image.png");
BitmapImage image2 = LoadImageToMemory(webRequest.GetResponse().GetResponseStream());

public BitmapImage LoadImageToMemory(string path)
{
        BitmapImage image = new BitmapImage();

        try
        {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            System.IO.Stream stream = System.IO.File.Open(path, System.IO.FileMode.Open);
            image.StreamSource = new System.IO.MemoryStream();
            stream.CopyTo(image.StreamSource);
            image.EndInit();

            stream.Close();
            stream.Dispose();
            image.StreamSource.Close();
            image.StreamSource.Dispose();
        }
        catch { throw; }

        return image;
}

// 或者使用 System.Net.WebRequest().GetResponse().GetResponseStream()

public BitmapImage LoadImageToMemory(System.IO.Stream stream)
    {
        if (stream.CanRead)
        {
            BitmapImage image = new BitmapImage();

            try
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = new System.IO.MemoryStream();
                stream.CopyTo(image.StreamSource);
                image.EndInit();

                stream.Close();
                stream.Dispose();
                image.StreamSource.Close();
                image.StreamSource.Dispose();
            }
            catch { throw; }

            return image;
        }

        throw new Exception("Cannot read from stream");
}
于 2012-12-11T11:08:38.200 回答
0

如果您使用System.Drawing命名空间,则从流中启动图像会更容易:

try
{
   var req = WebRequest.Create(photoUrl);

   using (var response = req.GetResponse())
   {
     using (var stream = response.GetResponseStream())
     {
       if (stream != null)
       {
         var image = Image.FromStream(stream);
       }
     }
   }
 }
 catch (Exception ex)
 {
   // handle exception
 }
于 2018-03-09T17:36:16.410 回答