【问题标题】:Performance of Image loading图像加载性能
【发布时间】:2015-05-07 09:08:29
【问题描述】:

几个小时以来,我一直在试验各种从文件加载图像的方法。请看看这两种方法:

    public Image SlowLoad(string path)
    {
        return Image.FromFile(path);
    }

    public Image FastLoad(string path)
    {
        using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
            return Image.FromStream(ms);  
    }

第二种方法快 2 倍。我在这里想念什么?为什么会这样?我无法相信 .NET 开发人员无法仅使用我编写的方法更快地实现 Image.FromFile。所以=>我在某个地方错了。请告诉我在哪里。为什么第二种方法几乎快 2 倍?我的代码完全正确吗? (线程安全等)。也许 Image.FromFile 更安全?

【问题讨论】:

  • 仅供参考:reference.microsoft.com
  • 您的第二种方法要求在读取之前将整个文件加载到内存中,而第一种方法(也许)不需要。也许 Image.FromFile() 已针对低内存占用进行了优化,因此它一次只从文件中加载一个小缓冲区。
  • public Image SuperFastLoad(string path) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path))) return Image.FromStream(ms, false, false); }
  • 恕我直言 Image.FromFile 可能会随机访问文件中不连续的偏移量,假设您的图像格式是一种可能发生这种跳转的格式。所以在Image.FromFile 的情况下,.NET BCL 的架构师不得不在内存消耗和时间之间做出妥协,他们选择了更少的内存消耗但更慢的加载。如果这是真的,那么Image.FromFile 会受到硬盘跳转速度的影响,当您读取内存中的整个文件然后让Image.FromStream 后面的算法进行跳转时,不会发生这种情况,这些跳转现在发生在 RAM 中跨度>
  • @Randolph - 不知道为什么它不起作用,以下在 LINQPad 中起作用:void Main() { ImageLoader l = new ImageLoader(); System.Drawing.Image t = l.SuperFastLoad(@"test.bmp"); Console.WriteLine(t.Size.ToString()); } // Define other methods and classes here public class ImageLoader { public System.Drawing.Image SuperFastLoad(string path) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path))) { return System.Drawing.Image.FromStream(ms, false, false); } } }

标签: c# image stream


【解决方案1】:

阿法伊克: 首先 Image.FromFile 包装了 GDI+ GdipLoadImageFromFile* 函数,它们有一个奇怪的生命。 GDI+ 图像在整个生命周期内保存并可以使用源(文件或流),有关它的一些详细信息http://support.microsoft.com/en-us/kb/814675。所以,这里有一些可能的“多文件 io”与“多流 io”。 MS Reference Source System.Drawing.Image 中也有一些有趣的评论:

http://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Image.cs,181

class Image {
    ............
    public static Image FromFile(String filename,
                                     bool useEmbeddedColorManagement) 
    {
        ............    
        //GDI+ will read this file multiple times. 
        ............
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2011-12-07
    • 1970-01-01
    • 2022-01-24
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多