Unable to use = operator in a "If" statement
Why can't I use = operator over here. Anyway to solve this problem ?
If PictureBox1.Image = My.Resources.pic001 Then
x = 1
Else
x = 0
End If
The error message is:
Operator '=' is not defined for types 'System.Drawing.Image' and 'System.Dra开发者_如何学Gowing.Bitmap'
Assuming that PictureBox1.Image references the same Image object as My.Resources.pic001, then you could use:
If Object.ReferenceEquals(PictureBox1.Image, My.Resources.pic001) Then
As the error message says, the operator '=' is not defined for the types you are comparing. i.e. it is not possible to compare a System.Drawing.Image to a System.Drawing.Bitmap
You will need to compare the images bit-by-bit or create a hash value for each one and compare those.
There is a thread here which has a C# example (it shouldn't be hard to convert to VB):
http://www.codeguru.com/forum/showthread.php?t=363130
EDIT: There might be another solution, I have not tried it and I don't know if, and it probably won't, work as expeted but there is an Equals()
method available on System.Drawing.Image
(and Bitmap
is derived from Image
). You might have some luck with that.
You can't compare Image
s to Bitmap
s, they are different things.
Try this code:
Option Strict On
Option Explicit On
Public Class Form1
Dim pbImage1 As Image = My.Resources.Swamp 'imported from a file called Swamp.jpg
Dim pbimage2 As Image = My.Resources.Dusty 'Imported from a file called Dusty.jpg
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
PictureBox1.Image = pbImage1
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If PictureBox1.Image Is pbImage1 Then
PictureBox1.Image = pbimage2
Else
PictureBox1.Image = pbImage1
End If
End Sub
End Class
精彩评论