Skip to content

Instantly share code, notes, and snippets.

@MrKWatkins
Last active May 7, 2018 16:43
Show Gist options
  • Save MrKWatkins/f64710c1f241977d6ec5840f82e75bad to your computer and use it in GitHub Desktop.
Save MrKWatkins/f64710c1f241977d6ec5840f82e75bad to your computer and use it in GitHub Desktop.
C# code to map the 24-bit colours in an image to the nearest 8 or 9-bit colours.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using JetBrains.Annotations;
namespace Elena.Compiler.Console
{
/// <summary>
/// Maps the colours in a bitmap to the nearest Next colour. Uses the palettes from <see cref="PaletteGenerator" />.
/// (https://gist.github.com/MrKWatkins/ea62814ed78b79edf8c5aa4902652ff3)
/// </summary>
public static class ColourMapper
{
public static void MapTo8Bit([NotNull] [PathReference] string input, [NotNull] [PathReference] string output) => MapTo8Bit(input, output, ImageFormat.Png);
public static void MapTo8Bit([NotNull] [PathReference] string input, [NotNull] [PathReference] string output, [NotNull] ImageFormat outputFormat)
{
Map(input, output, outputFormat, MapTo2Bits);
}
public static void MapTo9Bit([NotNull] [PathReference] string input, [NotNull] [PathReference] string output) => MapTo9Bit(input, output, ImageFormat.Png);
public static void MapTo9Bit([NotNull] [PathReference] string input, [NotNull] [PathReference] string output, [NotNull] ImageFormat outputFormat)
{
Map(input, output, outputFormat, MapTo3Bits);
}
private static void Map([NotNull] [PathReference] string input, [NotNull] [PathReference] string output, [NotNull] ImageFormat outputFormat, Func<byte, byte> bMap)
{
using (var source = (Bitmap) Image.FromFile(input))
using (var target = new Bitmap(source.Width, source.Height))
{
for (var x = 0; x < source.Width; x++)
{
for (var y = 0; y < source.Height; y++)
{
var originalColour = source.GetPixel(x, y);
var newColour = Color.FromArgb(MapTo3Bits(originalColour.R), MapTo3Bits(originalColour.G), bMap(originalColour.B));
target.SetPixel(x, y, newColour);
}
}
target.Save(output, outputFormat);
}
}
[Pure]
private static byte MapTo3Bits(byte component) => (byte) ((component >> 5) * PaletteGenerator.Step3Bit);
[Pure]
private static byte MapTo2Bits(byte component) => (byte) ((component >> 5) * PaletteGenerator.Step2Bit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment