检查按钮图像

时间:2014-02-03 23:15:28

标签: c# image button

我需要检查按钮是否没有图像(BackColor变为绿色)还是名为Atorre的图像(BackColor变为红色),继承我的代码:

public static bool IsEnemyOrEmptyA(Button check)
{
    var Atorre = teste.Properties.Resources.Atorre;
    bool res;
    if (check == null || check.Image == null)
    {
        res = true;
        check.BackColor = Color.Green;
        return res;
    }
    else if (check.Image == teste.Properties.Resources.Atorre)
    {
        res = true;
        check.BackColor = Color.Red;
        return res;
    }
    else
    {
        res = false;
        return res;
    }
}

但即使是其他图像,该按钮也会显示背景颜色为红色或没有任何颜色。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这是比较图像的唯一方法,你不应该比较图像,而是比较一些变量。

   private void button1_Click(object sender, EventArgs e)
    {
        var Atorre = Resource1.test;
        var DifferentImage = Resource1.test2;
        byte[] a = BitmapToBytes(Atorre);
        byte[] b = BitmapToBytes(DifferentImage);

        bool isEqual = true;

        if (a.Length == b.Length && a != null && b != null)
        {
            for (int i = 0; i < b.Length; i++)  //compare every byte
            {
                if (b[i] != a[i])
                {
                    isEqual = false;
                    break;
                }
            }
        }
        else
        {
            isEqual = false;
        }

        if(isEqual)
            MessageBox.Show("It's EQUAL");
        else
            MessageBox.Show("Not EQUAL");

    }


    //Convert Image to Bytes 
    public static byte[] BitmapToBytes(Bitmap Bitmap)
    {
        System.IO.MemoryStream ms = null;
        try
        {
            ms = new System.IO.MemoryStream();
            Bitmap.Save(ms, Bitmap.RawFormat);
            byte[] byteImage = new Byte[ms.Length];
            byteImage = ms.ToArray();
            return byteImage;
        }
        catch (ArgumentNullException ex)
        {
            throw ex;
        }
        finally
        {
            ms.Close();
        }
    }