使用GetPixel/SetPixel,我使用了以下功能来增强强调红色和紫色的图像过滤器:
for (int y = 0; y < bmpMain.Height; y++)
for (int x = 0; x < bmpMain.Width; x++)
{
bmpMain.GetPixel(x, y);
Color c = bmpMain.GetPixel(x, y);
int myRed = c.R, myGreen = c.G, myBlue = c.B;
myGreen -= 128;
if (myGreen < 0) myGreen = 0;
bmpMain.SetPixel(x, y, Color.FromArgb(255, myRed, myGreen, myBlue));
}使用LockBits,我已经将其替换为以下内容:
for (int counter = 1; counter < rgbValues.Length; counter += 3)
{
rgbValues[counter] -= 128;
if (rgbValues[counter] < 0) rgbValues[counter] = 0;
}但是,没有将绿色像素值减去128个,而是将添加到绿色值中。
如果我这么做:
for (int counter = 1; counter < rgbValues.Length; counter += 3)
{
rgbValues[counter] += 128;
if (rgbValues[counter] < 0) rgbValues[counter] = 0;
}128也被添加到绿色值中。得到的图像与我减去128的图像相同。
那么,如何获得应该简化的数学才能在LockBits中正常工作呢?
发布于 2015-06-02 03:57:37
假设rgbValues是一个字节数组,则语句
rgbValues[counter] -= 128;等于
rgbValues[counter] = (byte)(rgbValues[counter] - 128);因此,如果rgbValues[counter]等于零,它将被设置为(byte)(-128)。问题是,与int不同,byte数据类型是无符号,不能表示负值。正如EBrown所指出的,减法溢出并包装回128。
修复代码的一种方法是引入一个int类型的中间变量,以便您能够安全地容纳负值:
int myGreen = rgbValues[counter];
myGreen -= 128;
if (myGreen < 0) myGreen = 0;
rgbValues[counter] = (byte)myGreen;另一种方法是重写代码,首先避免负值:
rgbValues[counter] = rgbValues[counter] > 128
? (byte)(rgbValues[counter] - 128)
: (byte)0; https://stackoverflow.com/questions/30586318
复制相似问题