Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Last active September 22, 2017 18:01
Show Gist options
  • Save Buildstarted/fc7984ceda8aa64eab21d0d4c4c2c497 to your computer and use it in GitHub Desktop.
Save Buildstarted/fc7984ceda8aa64eab21d0d4c4c2c497 to your computer and use it in GitHub Desktop.
Sorting pixels by various methods
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
namespace PixelSort
{
class Program
{
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please specify a filename");
return;
}
var methods = new Dictionary<string, Func<Color[], Color[]>>(StringComparer.OrdinalIgnoreCase)
{
{"sum", (s) => s.OrderBy(c => c.R + c.G + c.B).ToArray()},
{"hue", s => s.OrderBy(c => c.GetHue()).ToArray() },
{"saturation", s => s.OrderBy(c => c.GetSaturation()).ToArray() },
{"brightness", s => s.OrderBy(c => c.GetBrightness()).ToArray() },
{"hash", s => s.OrderBy(c => c.GetHashCode()).ToArray() },
{"r", s => s.OrderBy(c => c.R).ToArray() },
{"g", s => s.OrderBy(c => c.G).ToArray() },
{"b", s => s.OrderBy(c => c.B).ToArray() },
};
var method = methods["sum"];
var vertical = false;
var filename = args[0];
if (args.Length >= 2 && methods.ContainsKey(args[1]))
{
method = methods[args[1]];
}
else if (args.Length >= 2)
{
Console.WriteLine("Unknown sorting method");
return;
}
else
{
Console.WriteLine("Defaulting to sorting method: sum");
}
if (args.Any(a => a.Equals("vertical") || a.Equals("v")))
{
vertical = true;
}
using (var bmp = new Bitmap(filename))
{
var arr = new Color[bmp.Width];
if (!vertical)
{
for (var y = 0; y < bmp.Height; y++)
{
for (var x = 0; x < bmp.Width; x++)
{
arr[x] = bmp.GetPixel(x, y);
}
arr = method(arr);
for (var x = 0; x < bmp.Width; x++)
{
bmp.SetPixel(x, y, arr[x]);
}
}
}
else
{
for (var x = 0; x < bmp.Width; x++)
{
for (var y = 0; y < bmp.Height; y++)
{
arr[y] = bmp.GetPixel(x, y);
}
arr = method(arr);
for (var y = 0; y < bmp.Height; y++)
{
bmp.SetPixel(x, y, arr[y]);
}
}
}
var info = new FileInfo(filename);
var c = 1;
while (true)
{
filename = Path.Combine(info.DirectoryName, $"{info.Name} ({c}){info.Extension}");
if (File.Exists(filename))
{
c++;
}
else
{
break;
}
}
bmp.Save(filename);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment