Last active
November 10, 2021 09:29
-
-
Save dkarzon/3f011099f27a92d3a243ce4d88fe6993 to your computer and use it in GitHub Desktop.
Console app that reads an image file and creates an excel file with each pixel colour info in the text and cell background (1 Pixel = 1 cell wide x 2 cells high)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Drawing; // Nuget System.Drawing.Common | |
using System.Linq; | |
using IronXL; // Nuget IronXL.Excel | |
namespace ImgToXlsx | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
WorkBook workbook = WorkBook.Create(); | |
WorkSheet sheet = workbook.CreateWorkSheet("image"); | |
Bitmap img = new Bitmap("Jace_37.png"); | |
sheet.InsertColumns(0, img.Width); | |
sheet.InsertRows(0, img.Height * 2); | |
for (int i = 0; i < img.Width; i++) | |
{ | |
for (int j = 0; j < (img.Height * 2); j += 2) | |
{ | |
Color pixel = img.GetPixel(i, j/2); | |
var color = ClosestColor(pixel); | |
var cell = sheet[GetRangeAddress(i, j) + ":" + GetRangeAddress(i, j + 1)]; | |
var hexColor = ColorTranslator.ToHtml(color); | |
cell.Value = hexColor; | |
cell.Style.BackgroundColor = hexColor; | |
cell.Style.SetBackgroundColor(color); | |
if (hexColor == "#20151B") | |
{ | |
cell.Style.Font.Color = "#FFFFFF"; | |
} | |
} | |
} | |
workbook.SaveAs("Result.xlsx"); | |
} | |
static readonly string[] _columns = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH" }; | |
static string GetRangeAddress(int x, int y) | |
{ | |
return _columns[x] + (y + 1); | |
} | |
static readonly List<Color> _colors = new List<Color> | |
{ | |
ColorTranslator.FromHtml("#FFFFFF"),//bg | |
ColorTranslator.FromHtml("#D6AE98"),//face | |
ColorTranslator.FromHtml("#20151B"),//shirt | |
ColorTranslator.FromHtml("#352A30"),//beard/hair light | |
ColorTranslator.FromHtml("#D0CCCC"),//teeth | |
ColorTranslator.FromHtml("#5C4C4E"),//glasses | |
ColorTranslator.FromHtml("#987070"),//mouth | |
}; | |
static Color ClosestColor(Color a) | |
{ | |
return _colors.OrderBy(c => ColorCloseness(c, a)).First(); | |
} | |
static int ColorCloseness(Color a, Color b) | |
{ | |
var rDist = Math.Abs(a.R - b.R); | |
var gDist = Math.Abs(a.G - b.G); | |
var bDist = Math.Abs(a.B - b.B); | |
return rDist + gDist + bDist; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment