I set my pictureBox with a default image from resources with this:
public Form1()
{
InitializeComponent();
pictureBox1.Image = Properties.Resources.default_Employee_Image;
}
when I check if the picture in the pictureBox is from resources with this code, it doesn't draw the border:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
//pictureBox border color
Color themeColor = Color.FromArgb(172, 188, 212);
if (pictureBox1.Image == null) //if image from db is null display default image
{
pictureBox1.Image = Properties.Resources.default_Employee_Image;
}
//if image is the default image: paint border
if (pictureBox1.Image == Properties.Resources.default_Employee_Image)
{
ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, themeColor, ButtonBorderStyle.Solid);
}
}
Also if image from the pictureBox is default, I'll save it as null in my database.
I want to only have a border if the default image is loaded. If I select another image the border should be gone.
If the pictureBox has the default image it should look like this (which means that I still have not selected a picture of the user):
But if the picture in my pictureBox is not the default image-(the image in my resources), [This means that I already selected an image] it should look like this:
And not like this:
pictureBox1.Image == Properties.Resources.SomeImage
will never return true
, because every time that you call Properties.Resources.SomeImage
, it returns a new instance of the image.
You don't need to track the assigned image; instead, you need to track the status. You can use either of the following options:
Rely on a flag: You can set a flag like bool isDefaultImage = true;
at form level and if at some point of your application you changed the image, set it to true. Something like this:
if(isDefaultImage)
{
//draw border
}
Rely on Model/DataSource: You can also rely on your model/data source values and instead of checking UI elements, check if the user has a profile picture. Something like this:
if(myUserObject.ProfilePicture == null)
{
//draw border
}
Compare two images
Anyhow, just in case you are interested to compare two Image
objects to see whether they are same Image, you can use the following method:
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);
}
Then you can use it like this:
using(var image = Properties.Resources.DefaultImage)
{
var isDefaultImage = AreImagesEqual(pictureBox1.Image, image);
if(isDefaultImage)
{
//draw border
}
}