HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Do my Image Widths Exceed Limit?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
widthsimagelimitexceed

Problem

I needed to find whether any image's width at or higher than a certain directory folder exceeds a limit. Is this code a good way of doing this, or is there a way in which it can be improved? I ran it over at least a couple hundred images and several hundred other files contained in the main directory (not C:\Users, but I don't want to show my user name), and it completed so fast the time is irrelevant.

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        Image img = Image.FromFile(file);

        if (img.Width > 1100)
        {
            Console.WriteLine(file);
            Console.WriteLine(img.Width);
        }

        img.Dispose();
    }
}

Solution

Rather than opening a resource and then remembering to close it with a .Dispose() call,
I think it's good to use the using (...) { ... } idiom as much as possible.
Some questions (and again) on Stack Overflow suggest some issues with releasing image resources when opened with Image.FromFile.

I propose this alternative:

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            if (img.Width > 1100)
            {
                Console.WriteLine(file);
                Console.WriteLine(img.Width);
            }
        }
    }
}

Code Snippets

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            if (img.Width > 1100)
            {
                Console.WriteLine(file);
                Console.WriteLine(img.Width);
            }
        }
    }
}

Context

StackExchange Code Review Q#83599, answer score: 4

Revisions (0)

No revisions yet.