Click here to Skip to main content
15,886,519 members
Articles / Programming Languages / C#

Reading Image Headers to Get Width and Height

Rate me:
Please Sign up or sign in to vote.
4.97/5 (16 votes)
28 Apr 2009CPOL3 min read 125.9K   2.6K   44  
Looks at techniques for getting an image's width and height quickly
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;

namespace DevWilson
{
    public class ImageOrientationThreaded
    {
        private int imagesRemaining;

        public List<string> Landscapes { get; private set; }

        public void GetLandscapeThreaded(List<string> paths)
        {
            this.Landscapes = new List<string>();
            this.imagesRemaining = paths.Count;

            foreach (string path in paths)
            {
                // add each path as a task in the thread pool
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadCallback), path);
            }


            // wait until all images have been loaded
            lock (this.Landscapes)
            {
                Monitor.Wait(this.Landscapes);
            }
        }

        private bool IsLandscape(string path)
        {
            using (Bitmap b = new Bitmap(path))
            {
                return b.Width > b.Height;
            }
        }

        private void ThreadCallback(object stateInfo)
        {
            string path = (string)stateInfo;
            bool isLandscape = this.IsLandscape(path);
           
            lock (this.Landscapes)
            {
                if (isLandscape)
                {
                    this.Landscapes.Add(path);
                }

                imagesRemaining--;

                if (imagesRemaining == 0)
                {
                    // all images loaded, signal the main thread
                    Monitor.Pulse(this.Landscapes);
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Play.com
United Kingdom United Kingdom
Hi, my name's Andy Wilson and I live in Cambridge, UK where I work as a Senior C# Software Developer.

Comments and Discussions