根据使用 ResX 资源设置的图像查找图片框



我一直在尝试检查PictureBox是否有特定的图像。我已经使用 Properties.Resources.TheImage 设置了PictureBox的形象。

使用以下代码PictureBox控件中都找不到图像。我一直在努力使它起作用:

foreach (Control X in Controls)
{
    if (X is PictureBox)
    {
        if (((PictureBox)X).Image == Properties.Resources.TheImage)
        {
            MessageBox.Show("found the image");
        }
    }
}

每次使用 Properties.Resources.XxxxYyy 属性时,它将始终返回一个新的位图。一般来说,内存使用量膨胀的令人讨厌的来源。您必须将其存储在表单构造函数的变量中,现在您可以比较它。

例:

Bitmap _icopalABitmap = Properties.Resources.IcopalA;
Bitmap _icopalBBitmap = Properties.Resources.IcopalB;

然后你检查特定图像

Properties.Resources.SomeImage每次使用它时都会返回不同的对象引用。你只需测试一下:

var b = object.ReferenceEquals(Properties.Resources.SomeImage, 
                               Properties.Resources.SomeImage);

要检查图像的相等性,可以使用此方法:

public bool AreImagesEqual(Image img1, Image img2)
{
    ImageConverter converter = new ImageConverter();
    byte[] bytes1 = (byte[])converter.ConvertTo(img1, typeof(byte[]));
    byte[] bytes2 = (byte[])converter.ConvertTo(img2, typeof(byte[]));
    return Enumerable.SequenceEqual(bytes1, bytes2);
}

例如:

var b = AreImagesEqual(Properties.Resources.SomeImage, 
                       Properties.Resources.SomeImage);

最新更新