My colleague just asked me about how to reduce the number of colors in image programmatically. This is a very simple task and contains of 43 steps:
First of all, you have to read a source image:
using (var img = Image.FromFile(name)) {
var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(
e => e.FormatID == ImageFormat.Bmp.Guid);
Then, create your own encoder with certain color depth (32 bits in this case):
var myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;
var myEncoderParameter = new EncoderParameter(myEncoder, 32L);
var myEncoderParameters = new EncoderParameters(1) {
Param = new EncoderParameter[] { myEncoderParameter } };
Then save it:
img.Save(name.Replace(".png", ".bmp"), bmpEncoder, myEncoderParameters);
It it enough? Not really, because if you’re going to lose colors (by reducing color depth), it makes sense to avoid letting default WIX decoder to do this, thus you have to find the nearest base colors manually. How to do this? By using simple math:
Color GetNearestBaseColor(Color exactColor) {
Color nearestColor = Colors.Black;
int cnt = baseColors.Count;
for (int i = 0; i < cnt; i++) {
int rRed = baseColors[i].R - exactColor.R;
int rGreen = baseColors[i].G - exactColor.G;
int rBlue = baseColors[i].B - exactColor.B;
int rDistance =
(rRed * rRed) +
(rGreen * rGreen) +
(rBlue * rBlue);
if (rDistance == 0.0) {
return baseColors[i];
} else if (rDistance < maxDistance) {
maxDistance = rDistance;
nearestColor = baseColors[i];
}
}
return nearestColor;
}
Now, you can either change colors on base image directly:
unsafe {
uint* pBuffer = (uint*)hMap;
for (int iy = 0; iy < (int)ColorMapSource.PixelHeight; ++iy)
{
for (int ix = 0; ix < nWidth; ++ix)
{
Color nc = GetNearestBaseColor(pBuffer[0].FromOle());
pBuffer[0] &= (uint)((uint)nc.A << 24) |
(uint)(nc.R << 16 ) |
(uint)(nc.G << 8 ) |
(uint)(nc.B );
++pBuffer;
}
pBuffer += nOffset;
}
}
Or, if you’re in WPF and .NET 3.5, create a simple pixel shader effect to do it for you in hardware. Now, my colleague can do it himself in about 5 minutes. Have a nice day and be good people.
Hello! My name is Tamir Khason, and I am software architect, project manager, system analyst and [of course] programmer. In addition to writing big amount of documentation, I also write code, a lot of code. I used to work as a freelance architect, project manager, trainer, and consultant here, in Israel, but recently
join the company with extremely persuasive idea - to make a world better place. I have very pretty wife and 3 charming kids, but unfortunately almost no time for them.
To be updated within articles, I publishing,
visit my blog or
subscribe RSS feed. Also you can
follow me on Twitter to be up to date about my everyday life.