Bit*_*ian 5 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) });
}
Run Code Online (Sandbox Code Playgroud)
然后我将此BitmapImage绑定到图像控件.
但我不确定设置UriSource是否实际将图像加载到内存中.
我还看到了BitmapImage的SetSourceAsync属性.但我不确定如何在我的上下文中使用它.任何人都可以帮助我使用SetSourceAsync属性或加载图像的最佳方式....
谢谢
因为我不想显示错误的答案,所以我必须在 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;
}
Run Code Online (Sandbox Code Playgroud)
// 或者使用 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");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5023 次 |
最近记录: |