比较两个图像-error对象当前正在其他地方使用
本文关键字:其他 方使用 对象 -error 图像 两个 比较 | 更新日期: 2023-09-27 18:25:05
我有一个大图像,我把它裁剪成小图像,并与打开的图像进行比较。它在没有线程的情况下正常运行。当我用线程运行时,它显示错误"Object当前正在其他地方使用。"
方法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())的其他行中警告错误;
这是因为Gdi+Image类不是线程安全的。使用前锁定图像:
Image DummyImage;
// Paint
lock (DummyImage)
e.Graphics.DrawImage(DummyImage, 10, 10);
// Access Image properties
Size ImageSize;
lock (DummyImage)
ImageSize = DummyImage.Size;