sort jpegs by average lightness in csharp

You can use the System.Drawing namespace to load the JPEG images and calculate the average lightness of each image. After that, you can sort the images based on their average lightness using LINQ.

Here's the code to load the JPEG images in a directory, calculate their average lightness, and sort them based on their lightness:

main.cs
using System;
using System.Drawing;
using System.IO;
using System.Linq;

class Program {
    static void Main(string[] args) {
        var directory = new DirectoryInfo(@"C:\Path\To\Directory");
        var images = directory.GetFiles("*.jpg", SearchOption.TopDirectoryOnly)
            .Select(fi => Image.FromFile(fi.FullName))
            .Select(img => {
                var lightness = GetAverageLightness(img);
                return new { lightness, img };
            })
            .OrderBy(x => x.lightness)
            .Select(x => x.img);
    
        // Use the sorted images
    }
    
    static double GetAverageLightness(Image image) {
        var bitmap = new Bitmap(image);
        var totalLightness = 0.0;
        for (var y = 0; y < bitmap.Height; y++) {
            for (var x = 0; x < bitmap.Width; x++) {
                var color = bitmap.GetPixel(x, y);
                var lightness = (color.R + color.G + color.B) / 3.0;
                totalLightness += lightness;
            }
        }
        var numPixels = bitmap.Width * bitmap.Height;
        return totalLightness / numPixels;
    }
}
1124 chars
35 lines

This code loads all JPEG images in the specified directory, calculates their average lightness using the GetAverageLightness method, and sorts them in ascending order by their lightness. The sorted images are then available in the images variable for further processing.

gistlibby LogSnag