C#图片处理之:色彩调整 .
其原理是每个象素的三个颜色分量同时增加或减少一个固定的值。现在更进一步,假如每个象素三个分量增加或减少的值不是相同的呢?嗯,这就今天要讨论的主题了。
应该很容易想明白,假如我们需要一张照片偏红一点,那只需要每个象素的红色分量值都增加就可以了。举个更实际一点的场景,比如要把一张鲜艳的彩色照片处理成泛棕的老旧黑白照,最简单的一个方法就是先把它处理成256级灰阶图,然后增加每个象素的红色分量。
老规矩,给出函数。
/**//// <summary>
/// 色彩调整
/// </summary>
/// <param name="bmp">原始图</param>
/// <param name="rVal">r增量</param>
/// <param name="gVal">g增量</param>
/// <param name="bVal">b增量</param>
/// <returns>处理后的图</returns>
public static Bitmap KiColorBalance(Bitmap bmp, int rVal, int gVal, int bVal)
...{
if (bmp == null)
...{
return null;
}
int h = bmp.Height;
int w = bmp.Width;
try
...{
if (rVal > 255 || rVal < -255 || gVal > 255 || gVal < -255 || bVal > 255 || bVal < -255)
...{
return null;
}
BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
...{
byte* p = (byte*)srcData.Scan0.ToPointer();
int nOffset = srcData.Stride - w * 3;
int r, g, b;
for (int y = 0; y < h; y++)
...{
for (int x = 0; x < w; x++)
...{
b = p[0] + bVal;
if (bVal >= 0)
...{
if (b > 255) b = 255;
}
else
...{
if (b < 0) b = 0;
}
g = p[1] + gVal;
if (gVal >= 0)
...{
if (g > 255) g = 255;
}
else
...{
if (g < 0) g = 0;
}
r = p[2] + rVal;
if (rVal >= 0)
...{
if (r > 255) r = 255;
}
else
...{
if (r < 0) r = 0;
}
p[0] = (byte)b;
p[1] = (byte)g;
p[2] = (byte)r;
p += 3;
}
p += nOffset;
}
} // end of unsafe
bmp.UnlockBits(srcData);
return bmp;
}
catch
...{
return null;
}
} // end of color
/// 色彩调整
/// </summary>
/// <param name="bmp">原始图</param>
/// <param name="rVal">r增量</param>
/// <param name="gVal">g增量</param>
/// <param name="bVal">b增量</param>
/// <returns>处理后的图</returns>
public static Bitmap KiColorBalance(Bitmap bmp, int rVal, int gVal, int bVal)
...{
if (bmp == null)
...{
return null;
}
int h = bmp.Height;
int w = bmp.Width;
try
...{
if (rVal > 255 || rVal < -255 || gVal > 255 || gVal < -255 || bVal > 255 || bVal < -255)
...{
return null;
}
BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
...{
byte* p = (byte*)srcData.Scan0.ToPointer();
int nOffset = srcData.Stride - w * 3;
int r, g, b;
for (int y = 0; y < h; y++)
...{
for (int x = 0; x < w; x++)
...{
b = p[0] + bVal;
if (bVal >= 0)
...{
if (b > 255) b = 255;
}
else
...{
if (b < 0) b = 0;
}
g = p[1] + gVal;
if (gVal >= 0)
...{
if (g > 255) g = 255;
}
else
...{
if (g < 0) g = 0;
}
r = p[2] + rVal;
if (rVal >= 0)
...{
if (r > 255) r = 255;
}
else
...{
if (r < 0) r = 0;
}
p[0] = (byte)b;
p[1] = (byte)g;
p[2] = (byte)r;
p += 3;
}
p += nOffset;
}
} // end of unsafe
bmp.UnlockBits(srcData);
return bmp;
}
catch
...{
return null;
}
} // end of color