将图像加载到内存的最佳方法?

时间:2012-12-11 09:51:12

标签: c# xaml windows-8 windows-runtime winrt-xaml

我在项目的资源文件夹中有很多图像,我需要在应用程序启动时加载到内存中。减少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属性或加载图像的最佳方法....

由于

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:0)

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

System.Drawing