using System.Collections.Generic; namespace Palettizer { public class Palette { public Dictionary ColorToGrayscaleMap { get; } public byte GrayscaleIndex { get; set; } public List AlternateColorRows { get; } public int Width { get => ColorToGrayscaleMap.Count; } public int Height { get => AlternateColorRows.Count + 1; } public Palette() { ColorToGrayscaleMap = new Dictionary(); GrayscaleIndex = 0; AlternateColorRows = new List(); } public void AddColor(Color color, byte grayscaleIndex) { ColorToGrayscaleMap.Add(color, grayscaleIndex); } public void AddAlternateColorRow(Color[] colors) { var byteArray = new byte[ColorToGrayscaleMap.Count * 4]; foreach (var color in colors) { if (ColorToGrayscaleMap.ContainsKey(color)) { var grayscaleIndex = ColorToGrayscaleMap[color]; byteArray[grayscaleIndex] = color.R; byteArray[grayscaleIndex + 1] = color.G; byteArray[grayscaleIndex + 2] = color.B; byteArray[grayscaleIndex + 3] = color.A; } else { System.Console.WriteLine("That color doesn't exist in the grayscale palette!! Bailing!!!"); } } AlternateColorRows.Add(byteArray); } public byte[] CreateIndexedPaletteBitmap() { var paletteBitmap = new byte[ColorToGrayscaleMap.Count * 4 * (AlternateColorRows.Count + 1)]; var index = 0; foreach (KeyValuePair kv in ColorToGrayscaleMap) { var color = kv.Key; var grayscale = kv.Value; paletteBitmap[index] = grayscale; paletteBitmap[index + 1] = grayscale; paletteBitmap[index + 2] = grayscale; paletteBitmap[index + 3] = 255; var alternateIndex = 1; foreach (var alternateColorRow in AlternateColorRows) { for (var j = 0; j < ColorToGrayscaleMap.Count * 4; j += 4) { paletteBitmap[index + (ColorToGrayscaleMap.Count * alternateIndex)] = alternateColorRow[j]; paletteBitmap[index + 1 + (ColorToGrayscaleMap.Count * alternateIndex)] = alternateColorRow[j + 1]; paletteBitmap[index + 2 + (ColorToGrayscaleMap.Count * alternateIndex)] = alternateColorRow[j + 2]; paletteBitmap[index + 3 + (ColorToGrayscaleMap.Count * alternateIndex)] = alternateColorRow[j + 3]; } alternateIndex += 1; } index += 4; } return paletteBitmap; } } }