我想更改图像中140至180之间范围内的像素。因此,我使用了以下代码。但它只保存原始图像,而不是更改后的图像。请帮助我将图像的像素在140到180之间转换为0(黑色)。下面我的代码:将特定范围的像素值更改为c中所需的值#
public void convertImage(string imag)//some file path
{
using (Bitmap image = new System.Drawing.Bitmap(imag))
{
BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
IntPtr ptr = data.Scan0;
int size = data.Stride * image.Height;
byte[] bytes = new byte[size];
Marshal.Copy(ptr, bytes, 0, bytes.Length);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
if (
(140 < bytes[(y * data.Stride) + (x * 3) + 2]) && (180 > bytes[(y * data.Stride) + (x * 3) + 2]) &&
(140 < bytes[(y * data.Stride) + (x * 3) + 1]) && (180 > bytes[(y * data.Stride) + (x * 3) + 1]) &&
(140 < bytes[(y * data.Stride) + x * 3]) && (180 > bytes[(y * data.Stride) + x * 3])
)
{
bytes[(y * data.Stride) + (x * 3) + 2] = (int)0;
bytes[(y * data.Stride) + (x * 3) + 1] = (int)0;
bytes[(y * data.Stride) + x * 3] = (int)0;
}
}
}
Marshal.Copy(bytes, 0, ptr, bytes.Length);
image.UnlockBits(data);
image.Save("sys.bmp", ImageFormat.Bmp);
image.Dispose();
}
}
这里我假设我的图像是灰色像素在140到180之间的每种颜色。请帮帮我。
你有没有在调试器中通过这个步骤?你知道你正在进入'if'块吗? – adv12
完成后,您检查更改的图像是什么?原始图像或“sys.bmp”? – adv12
Invoque UnlockBits在您的第一个Marshal.Copy之后。另外,不需要处理你的图像,使用声明是为了它。 –