C# 如何实现惰性位图加载?
我想编写一个函数,该函数将获取作为输入字符串的文件名,并返回一个ImageDrawing对象。C# 如何实现惰性位图加载?,c#,.net,wpf,xaml,lazy-evaluation,C#,.net,Wpf,Xaml,Lazy Evaluation,我想编写一个函数,该函数将获取作为输入字符串的文件名,并返回一个ImageDrawing对象。 我不想在此函数中从磁盘加载位图。相反,我想做一些懒惰的评估。 为了找出尺寸,我使用了位图类 目前我有以下代码: public static ImageDrawing LoadImage(string fileName) { System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName); Sys
我不想在此函数中从磁盘加载位图。相反,我想做一些懒惰的评估。 为了找出尺寸,我使用了位图类 目前我有以下代码:
public static ImageDrawing LoadImage(string fileName)
{
System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
System.Drawing.Size s = b.Size ;
System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.Absolute));
return im;
}
编辑: 有许多很好的答案可能对社区有帮助-使用Lazy类并使用任务打开它
然而,我想把这个图像绘制放在绘图组中,然后序列化,所以懒惰以及任务对我来说不是一个选项 我建议在你的课堂上使用定时器,以“懒惰”的方式下载你的图片。此外,您还可以尝试在计时器滴答声事件内执行的任务。位图的构造函数并不懒惰,但您可以使用专门为该目的而创建的
懒惰
类:
public static Lazy<ImageDrawing> LoadImage(string fileName)
{
return new Lazy<ImageDrawing>(() => {
System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
System.Drawing.Size s = b.Size;
System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.Absolute));
return im;
});
}
公共静态延迟加载映像(字符串文件名)
{
返回新的延迟(()=>{
System.Drawing.Bitmap b=新的System.Drawing.Bitmap(文件名);
系统图纸尺寸s=b.尺寸;
System.Windows.Media.ImageDrawing im=新的System.Windows.Media.ImageDrawing();
im.Rect=new System.Windows.Rect(0,0,s.宽度,s.高度);
im.ImageSource=new System.Windows.Media.Imaging.BitmapImage(新Uri(文件名,UriKind.Absolute));
返回即时消息;
});
}
从文件中(http://msdn.microsoft.com/en-us/library/dd997286.aspx):
尽管您可以编写自己的代码来执行惰性初始化,但我们建议您改用惰性初始化。Lazy及其相关类型还支持线程安全,并提供一致的异常传播策略
相关:谢谢你的建议,它可能对其他人有用-所以(+1)。对我来说,它没有用,因为我需要序列化BitmapImage,我不想序列化任务,请参见。。。好那就不用做任何任务了。但是,您可以尝试重新查看您的类并实现所有您需要的东西。事实上,要做一些工作的班级应该是另一个班级。并将数据/图像保存在类中,该类没有任何转换方法。我的意思是尝试将数据和方法拆分为2个不同的类。(+1)为社区提供有用的答案。但这对我来说并不好,特别是,我已经更新了我的问题-请在我尝试用此代码序列化的实例时检查它var img=LoadImage(“C:\\Windows\\Account.png”);Stream=File.Open(“Serialized.osl”,FileMode.Create);BinaryFormatter bformatter=新的BinaryFormatter();序列化(流,img);stream.Close();`。。。我收到错误消息“System.Windows.Media.ImageDrawing”不可序列化。如果没有
Lazy
wrapper,您将得到相同的消息。。。您如何尝试序列化此内容?必须将Value属性传递给序列化程序:System.Windows.Markup.XamlWriter.Save(img.Value)代码>但这样它就不会懒惰了。值将被初始化。在您序列化的那一刻,它将始终被初始化:)也许您可以告诉我们您试图在更广泛的上下文中实现什么?