比较两个图像 - 错误对象目前正在其他地方使用

时间:2012-02-20 07:35:14

标签: c# .net multithreading bitmap

我有一张大图像,我把它裁剪成小图像并与打开的图像进行比较。 没有Thread就运行正常。 当我使用线程运行它显示错误“对象当前正在其他地方使用。”

方法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;
    }

方法比较Img

        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 个答案:

答案 0 :(得分:1)

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

Image DummyImage;

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

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