Hi, this is exactly what I was looking for so I made a couple tweaks. Now it sorts colors by most common found in the image and limits them to the palette limit which is 96. It shouldn't give I/O errors d crash but in case you're using non-english pdn this will make another, not localized, folder named "Palettes".
// Name:
// Submenu:
// Author:
// Title:
// Version:
// Desc:
// Keywords:
// URL:
// Help:
// Force Single Render Call
// creates file with colors
void MakePaletteFile(List<string> colors)
{
int fileCount = 0;
string fileName = "UntitledPalette";
string paletteDir = Path.Combine(this.Services.GetService<IUserFilesService>().UserFilesPath, "Palettes");
if (!Directory.Exists(paletteDir))
Directory.CreateDirectory(paletteDir);
string path = Path.Combine(paletteDir, fileName + ".txt");
while (File.Exists(path))
{
fileCount++;
path = Path.Combine(paletteDir, $"{fileName}{fileCount}.txt");
}
colors.Insert(0, $"; {colors.Count} unique color(s)");
File.WriteAllLines(path, colors);
}
void Render(Surface dst, Surface src, Rectangle rect)
{
List<ColorBgra> colors = new List<ColorBgra>();
ColorBgra currentPixel;
for (int y = rect.Top; y < rect.Bottom; y++)
{
if (IsCancelRequested) return;
for (int x = rect.Left; x < rect.Right; x++)
{
currentPixel = src[x,y];
colors.Add(currentPixel);
}
}
List<string> colorCodes = colors
.GroupBy(color => color)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(color => color.Count)
.Select(color => color.Value)
.Take(96)
.ToList()
.ConvertAll<string>(c => c.ToHexString());
MakePaletteFile(colorCodes);
}