我正在创建一种名为DIF(字典图像格式)的图像格式,其中图像指定图像中的调色板(字典),或者可以选择加载外部调色板。
我正在尝试为RGB光谱中的所有可能值创建颜色字典。我已经找到了如何遍历RGB频谱,但是如何遍历所有可能的字典键却不知所措。
每个字典键将由一串大小写字母(如aAaAB)组成,长度为五个字母。这提供了380204032种可能的组合,足以编码RGB中的1670万种颜色。
这将如何工作,以及如何将其与我现有的RGB代码集成,如下所示:
Dictionary<string,Color> rgb = new Dictionary<string,Color>();
for(int r = 0; r <= 255; r++)
{
for(int g = 0; g <= 255; g++)
{
for(int b = 0; b <= 255; b++)
{
//Add colors to dictionary here
}
}
}
答案 0 :(得分:1)
我建议你根本不需要字典。
相反,您可以根据需要将每种颜色转换为基本52(a-zA-Z)表示法。
这是一个例子。它使用了一些基本转换代码:Quickest way to convert a base 10 number to any base in .NET?
using System;
using System.Drawing;
namespace Demo
{
internal class Program
{
private void run()
{
// As an example, iterate through all known colours and demonstrate
// that we can convert each colour to a 5 character string and back.
var colors = Enum.GetValues(typeof(KnownColor));
foreach (KnownColor knowColor in colors)
{
Color colour = Color.FromKnownColor(knowColor);
string colourString = ColourToBase52(colour);
Color decodedColour = ColourFromBase52(colourString);
if (colour.ToArgb() != decodedColour.ToArgb())
Console.WriteLine("ERROR with colour " + colour); // Expect this to complain about TRANSPARENT.
else
Console.WriteLine("{0,-30} is represented by {1}", colour, colourString);
}
}
public static string ColourToBase52(Color colour)
{
int value = colour.ToArgb() & 0x00FFFFFF; // Mask off the alpha channel.
return ToBase52(value);
}
public static Color ColourFromBase52(string colour)
{
int value = FromBase52(colour);
return Color.FromArgb(unchecked((int)(0xFF000000 | value)));
}
public static string ToBase52(int value)
{
char[] baseChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
int targetBase = baseChars.Length;
int i = 32;
char[] buffer = new char[i];
do
{
buffer[--i] = baseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
char[] result = new char[32 - i];
Array.Copy(buffer, i, result, 0, 32 - i);
return new string(result).PadLeft(5, 'a');
}
public static int FromBase52(string value)
{
char[] baseChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
int targetbase = baseChars.Length;
int multiplier = 1;
int result = 0;
for (int i = value.Length-1; i >= 0; --i)
{
int digit = Array.IndexOf(baseChars, value[i]);
result += digit*multiplier;
multiplier *= targetbase;
}
return result;
}
public static void Main()
{
new Program().run();
}
}
}