2017-05-22 31 views
0

我想更改图像中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之间的每种颜色。请帮帮我。

+0

你有没有在调试器中通过这个步骤?你知道你正在进入'if'块吗? – adv12

+0

完成后,您检查更改的图像是什么?原始图像或“sys.bmp”? – adv12

+0

Invoque UnlockBits在您的第一个Marshal.Copy之后。另外,不需要处理你的图像,使用声明是为了它。 –

回答

2

替代ImageLockMode ReadWrite而不是ReadOnly

BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 
+1

哈!这一点很明显,一旦它被指出! +1。 – adv12

+0

哦超,它的工作非常感谢你。 –

+0

@subrahmanyeswaraswamymurala谢谢!请回答正确的答案。 –