Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Image loading

Tags:

c#

stream

image

I've been experimenting for a few hours with various ways to load an image from file. Please have a look at these two methods:

    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);  
    }

The second method is like 2 times faster. What am I missing here? Why is it so? I can't believe that .NET developers couldn't implement Image.FromFile faster simply using the method I wrote. So => I am wrong somewhere. Please tell me where. Why is the second method almost 2 times faster? Is my code fully correct? (thread-safe, etc.). Maybe Image.FromFile is more secure?

like image 424
Patryk Golebiowski Avatar asked Nov 01 '22 08:11

Patryk Golebiowski


1 Answers

AFAIK: First of all Image.FromFile wraps GDI+ GdipLoadImageFromFile* functions, ones has a strange life. GDI+ image holds and can use source (file or stream) during whole lifetime, some details about it http://support.microsoft.com/en-us/kb/814675. So, here is some possible "multiple file io" vs "multiple stream io". Also there is some interesting comment in 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. 
        ............
    }
}
like image 79
Ilia Maskov Avatar answered Dec 01 '22 21:12

Ilia Maskov