I currently write a program which indexes an image to 16 colors, correcting its background-color and correcting the image itself afterwards. To "write pixels" I coded a little method:
Expand|Select|Wrap|Line Numbers
- void SetPixel(Bitmap bmp, int x, int y, Color c)
- int i;
- int min = int.MaxValue;
- int minI = 0;
- for (i = 0; i < 256; i++)
- {
- Color cPal = bmp.Palette.Entries[i];
- int r = c.R - cPal.R;
- int g = c.G - cPal.G;
- int b = c.B - cPal.B;
- int d = r * r + g * g + b * b;
- if (d == 0) break;
- if (d < min)
- {
- min = d;
- minI = i;
- }
- }
- if (i == 256) i = minI;
- BitmapData bmpData = bmp.LockBits(new Rectangle(x, y, 1, 1),
- ImageLockMode.ReadOnly,
- bmp.PixelFormat);
- Marshal.WriteByte(bmpData.Scan0, (byte)i);
- bmp.UnlockBits(bmpData);
It works with 8bpp images but not with 4bpp! help :(
As you can see, the image is kind of cut every 2nd pixel.
(Note: Left one is INPUT; right is OUTPUT)