Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created November 6, 2019 20:30
Show Gist options
  • Select an option

  • Save davidwhitney/3c36beb4cecd2dc570d08dea2ee5d6cc to your computer and use it in GitHub Desktop.

Select an option

Save davidwhitney/3c36beb4cecd2dc570d08dea2ee5d6cc to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace reducer
{
class Program
{
static void Main(string[] args)
{
using (var rawMap = Image.Load<Rgba32>("C:\\Users\\David Whitney\\OneDrive\\Desktop\\cat.jpg"))
{
var asString = ImageTranscoder.Render(rawMap);
Console.WriteLine(asString);
}
}
}
public class ImageTranscoder
{
private static readonly Dictionary<float, string> Map;
public static string Render(Image<Rgba32> image)
{
image = ResizeAllSmallLike(image);
var sb = new StringBuilder();
var pallet = new List<Rgba32>();
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var pixel = image[x, y];
if (!pallet.Contains(pixel))
{
pallet.Add(pixel);
}
var index = pallet.IndexOf(pixel);
sb.Append(index.ToString().PadLeft(3, '0') + " ");
}
sb.Append(Environment.NewLine);
}
Console.WriteLine("var pallet = [");
foreach (var item in pallet)
{
Console.WriteLine(item);
}
Console.WriteLine("];");
return PostProcessOutput(sb);
}
private static Image<Rgba32> ResizeAllSmallLike(Image<Rgba32> image)
{
if (image.Width <= 100 || image.Height <= 100)
{
return image;
}
var clone = image.Clone(i => i.Resize(10, 10));
var memoryStream = new MemoryStream();
clone.SaveAsJpeg(memoryStream);
memoryStream.Position = 0;
File.WriteAllBytes("C:\\Users\\David Whitney\\OneDrive\\Desktop\\cat2.jpg", memoryStream.ToArray());
return clone;
}
private static string PostProcessOutput(StringBuilder sb)
{
var output = sb.ToString();
output = output.Replace("000", " ");
sb.Clear();
output = output.Substring(0, output.Length - Environment.NewLine.Length);
return output;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment