2012-02-20 47 views
-1

我有1个大图像,我把它裁剪成小图像并与打开的图像比较。 无线程运行正常。 当我与线程运行它显示错误“对象目前正在其他地方使用。”比较两个图像 - 错误对象目前正在其他地方使用

方法CropBitmap

 public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight) 
    { 
     Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight); 
     Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat); 
     return cropped; 
    } 

方法比较图

 public bool ImageCompareString(Bitmap firstImage, Bitmap secondImage) 
    { 
     int x, y; 
     int count = 0; 

     // Loop through the images pixels to reset color. 
     for (x = 0; x < firstImage.Width; x++) 
     { 
      for (y = 0; y < firstImage.Height; y++) 
      { 
       Color pixelColor1 = firstImage.GetPixel(x, y); 
       Color pixelColor2 = secondImage.GetPixel(x, y); 
       if (pixelColor1 != pixelColor2) 
       { 
        count++; 
       } 
      } 
     } 

     if (count > 400) 
     { 
      return false; 
     } 
     else 
     { 
      return true; 
     } 
    } 

主题

 void compare() 
    { 
     Bitmap captchaFull = new Bitmap(@"C:\Documents and Settings\Administrator\My Documents\largeImg.bmp"); 
     Bitmap pic1 = new Bitmap(openFileDialog1.FileName); 

     for (int x = 0; x < captchaFull.Width; x = x + 53) 
     { 
      for (int y = 0; y < captchaFull.Height; y = y + 44) 
      { 
       Bitmap temp = CropBitmap(captchaFull, x, y, 53, 44); 
       pxImg2.Image = temp; 
       if (ImageCompareString(temp, pic1)) 
       { 
        pxImg2.Image = temp; 
        return; 
       } 
      } 
     } 
    } 

更新1:

    Image check; 
       lock (pxImg2) 
       { 
        check = pxImg2.Image; 

        if (ImageCompareString(pic1, new Bitmap(check))) 
        { 
         pxImg2.Image = new Bitmap(check); 
         return; 
        } 
       } 

我锁定pxImg2但它仍然是错误 它警告在其他地方行错误Application.Run(new Form1());

回答

1

这是因为Gdi + Image类不是线程安全的。使用前锁定图像:

Image DummyImage; 

// Paint 
lock (DummyImage) 
    e.Graphics.DrawImage(DummyImage, 10, 10); 

// Access Image properties 
Size ImageSize; 
lock (DummyImage) 
    ImageSize = DummyImage.Size; 
+0

查看我的更新。它仍然是错误的。 – coder0410 2012-02-20 13:27:54

+0

尝试锁定'check'而不是pxImg2 – 2012-02-21 05:05:49