将图片框中的图像与默认图像进行比较

时间:2017-07-27 08:51:42

标签: c# winforms if-statement default picturebox

我将Picturebox.Image分配给默认图片。但它仍然通过If语句并打开新的Diaglog。我不知道为什么?请帮帮我!

private void saveBtn_Click(object sender, EventArgs e)
{
    if (imgBox.Image == Properties.Resources.DefaultImage || imgBox.Image == Properties.Resources.EmptyPhoto)
    {
        MessageBox.Show("Warning! Cannot save this image!");
    }
    else
    {
        SaveNoti save = new SaveNoti();
        save.sender = new SaveNoti.SEND(Task_functions);
        save.ShowDialog();
    }
}

2 个答案:

答案 0 :(得分:1)

因为每次从资源中读取图片时,您都会获得新副本,然后==将返回false(因为它显然会通过引用进行比较)。如果您将使用GDI +图形资源中的位图......您最好记住这一点。

将它们保存在某处:

static readonly Image DefaultImage = Properties.Resources.DefaultImage;
static readonly Image EmptyPhone = Property.Resources.EmptyPhoto;

然后务必始终使用分配imgBox.Image属性(您指定默认值):

imgBox.Image = DefaultImage; // Do not use Properties.Resources.DefaultImage

现在您可以检查相等性(在点击处理程序内):

if (imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto)
{
    MessageBox.Show("Warning! Cannot save this image!");
}

如果您多次使用它,只需提取一个方法:

private bool IsDefaultImage
    => imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto;

答案 1 :(得分:0)

这不对!这是我的代码:

static readonly Image DefaultImage = Properties.Resources.DefaultImage;
static readonly Image EmptyPhone = Property.Resources.EmptyPhoto;  
private void saveBtn_Click(object sender, EventArgs e)
        {
            imgBox.Image.Dispose();
            imgBox.Image = DefaultImage;
            if (imgBox.Image == DefaultImage)
            {
                MessageBox.Show("Warning! Cannot save this image!");
            }
            else
            {
                SaveNoti save = new SaveNoti();
                save.sender = new SaveNoti.SEND(Task_functions);
                save.ShowDialog();
            }

imgBox.Image = DefaultImage;行的结果是参数无效