C# 将图片框中的图像与默认图像进行比较
我将C# 将图片框中的图像与默认图像进行比较,c#,winforms,if-statement,default,picturebox,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) { Message
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();
}
}
因为每次从资源中读取图像时,您都会得到一个新副本,然后
=
将返回false
(因为它显然通过引用进行比较)。如果您要使用GDI+图形资源中的位图,最好记住这一点
把它们保存在某个地方:
static readonly Image DefaultImage = Properties.Resources.DefaultImage;
static readonly Image EmptyPhone = Property.Resources.EmptyPhoto;
然后确保始终使用它们分配imgBox.Image
属性(在其中分配默认值):
现在可以检查相等性(在单击处理程序中):
如果您多次使用它,只需提取一个方法:
private bool IsDefaultImage
=> imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto;
这是不对的!这是我的代码:
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行的结果代码>is参数无效等式正在比较引用。您需要实现图像的equals,然后比较ByTestStreams。尽管如此,如果只是对映像进行了一个微小的更改,ByTestStream将不同,equals检查将失败。您可能应该为您的问题找到不同的解决方案。@HuuTin我假设属性.Resources.DefaultImage
是图像
或位图
(以及其他一些东西,因为我看不到您的代码),除非您发布整个项目,否则您应该适应您的具体情况,不是吗???顺便问一下,那个警告是什么?布尔值?嗯…我不喜欢这种方式。你最好把整件事抽象出来(引入一个单独的类DefaultImages
,包含所有相关逻辑,但…无论如何,由您自己来评论您的代码:不要处理以前的图像,您每次都不创建新图像,那么它在运行时将失败。顺便说一句,分配不必在单击处理程序中,但当您分配图像时…:OIs是编译器警告吗r运行时错误?在这两种情况下,请发布完整的错误消息。另外:不要处理映像(我们正在重用它)和(同样重要)不要在单击处理程序中分配默认映像(您应该只在其中执行比较…),我理解,但…您应该在分配新映像之前(不是在保存之前)进行处理(没错)仅当它不是默认图像时(由于您发现的问题,无法每次重新创建默认图像)。单击处理程序中的“分配”将始终不保存而退出(如果代码是您发布的代码)
private bool IsDefaultImage
=> imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto;
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();
}