I created a windows form that displays and image as a Logo. I was able to browse and display an image to the PictureBox with this code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
I want the placed image saved in that PictureBox to be displayed every time the Form is called. What code do I need to write in order to do that?
On the load event of the form you can set the image of the picture box. By going to project settings, Resources tab, you can add an image as a Resource and reference it using the ProjectNamespace.Resources.NameOfResource.
You need a special kind of pictureBox that shows the logo. Let's call this a LogoBox. If you make this a user control you can use Visual Studio Toolbox to add it to your controls.
In Visual Studio:
Your LogoBox class will need a property to change the image that will be used as a logo. I use the same function as PictureBox.Image, but call it Logo:
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
}
}
This code is not enough: the next time you load this LogoBox you want it to load its last set Logo. The esiest method is to save the last set image in a file, because then you know certain that if the user of your LogoBox deletes the original image after setting it you still have your own saved copy.
.
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
image.Save(Properties.Settings.Default.LogoFileName)
}
}
Finally load the image when your LogoBox is loaded:
private void OnFormLoading(object sender, EventArgs e)
{
var img = Image.FromFile(Properties.Settings.Default.LogoFileName);
this.pictureBox1.Image = img;
}
Don't use this.Logo = img, because that will save the image again which is a waste of time.
The only thing to do is error handling if the logo file does not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With