TGE.Color[] GetColorTable(Bitmap bmp) { BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int bytesPerPixel = 4; int byteCount = bitmapData.Stride * bmp.Height; byte[] bytes = new byte[byteCount]; IntPtr ptrFirstPixel = bitmapData.Scan0; Marshal.Copy(ptrFirstPixel, bytes, 0, bytes.Length); int heightInPixels = bitmapData.Height; int widthInBytes = bitmapData.Width * bytesPerPixel; TGE.Color[] colors = new TGE.Color[bmp.Width * bmp.Height]; for (int y = 0; y < heightInPixels; y++) { int currentLine = y * bitmapData.Stride; for (int x = 0; x < widthInBytes; x += bytesPerPixel) { byte B = bytes[currentLine + x]; byte G = bytes[currentLine + x + 1]; byte R = bytes[currentLine + x + 2]; colors[x / bytesPerPixel + y * Width] = TGE.Color.FromArgb(R, G, B); } } bmp.UnlockBits(bitmapData); return(colors.Distinct().ToArray()); }
short GetClosestColorIndex(TGE.Color c) { short closestColorIndex = 0; float closestDist = float.MaxValue; for (short i = 0; i < ColorTable.Length; i++) { float dist = GetColorSqrDist(ColorTable[i], c); if (dist < closestDist) { closestColorIndex = i; closestDist = dist; } } return(closestColorIndex); }
float GetColorSqrDist(TGE.Color c1, TGE.Color c2) { return((((c2.R - c1.R) * 0.30f) * ((c2.R - c1.R) * 0.30f)) + (((c2.G - c1.G) * 0.30f) * ((c2.G - c1.G) * 0.30f)) + (((c2.B - c1.B) * 0.30f) * ((c2.B - c1.B) * 0.30f))); }