How to permanently display the placed image - c#

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:
Open the project where the LogoBox is to be used, or put it in a DLL, so it can be used by several executables.
Menu: Project - Add User Control, Name it LogoBox
Use the Toolbox to add a PictureBox to the user control.
Change the Dock style of picture box to DockStyle.Fill
Use properties to add an event handler for the Load Event, let's call it OnLoad.
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.
You'll need a filename for the file. User project properties - settings to create a filename.
Make it a string property with application scope (it will never change)
Name: LogoFileName
Value: think of something nice. Logo.Img?
.
[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.

Then lets have a static thing.
Within your form, implement a static paths for your image..say
public string prg_form_image
{
get { return "myimage.jpg"; }
}
public string prg_image_path
{
get { return this.AppDomain.CurrentDomain.BaseDirectory + "image\\"; }
}
private string myImage
{
get
{
return File.Exists(prg_image_path + prg_form_image)
? prg_image_path + prg_form_image
: prg_image_path + "default.jpg";
}
}
public Image img
{
get { return Image.FromFile(prg_image_path + prg_form_image); }
}
private void SetImage()
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
}
private void Form_Load(object sender, EventArgs e)
{
SetImage();
}
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)
{
if(File.Exists(prg_image_path + prg_form_image))
{
File.Delete(prg_image_path + prg_form_image);
}
if(!Directory.Exists(prg_image_path)) { Directory.Create(prg_image_path); }
Image imgIn = Image.FromFile(ofd.FileName);
imgIn.SaveAs(prg_image_path + prg_form_image);
SetImage();
}
}
Notes : Folder name image should exists along-side your executable program. a default.jpg should also exist inside the folder image.

Related

How to cache images from PictureBox in C# winform

Im trying to load images from a website. It loads very slowly. Everytime its selected. Any way to cache the image.
picturebox1.ImageLocation = "http://example.com/Image.jpg";
That form will be opened many times frequently, right now each time form is opened, images are being downloaded every time. It is unnecessary increasing traffic.
Is it possible to tell PictureBox to cache image (as Browser do), so next time same images is requested, it should load quickly. Is this possible?
if (listBox1.SelectedIndex == 0)
{
richTextBox1.Text = "Explore any game with Dex";
Image img = Image.FromFile("https://i.imgur.com/Jb6lTp1.png");
pictureBox1.Image = img;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
It says given path format is not supported
Try this way:
First Create a function to check whether file exist or not. If exist then simply load the file from local path else download the file from URL and store it in local.
//Function to validate the local cache file
private Image load_image()
{
Image img=null;
if(!(File.Exists(#"d:\samp.png")))
{
using (HttpClient httpclient= new HttpClient())
{
var response = httpclient.GetAsync(#"https://i.imgur.com/Jb6lTp1.png");
if (!response.Result.IsSuccessStatusCode)
{
return img;
}
using (var fs= new FileStream(#"d:\samp.png",FileMode.CreateNew)) // Path can be added as parameter of function
{
response.Result.Content.CopyToAsync(fs);
}
}
}
img = Image.FromFile(#"d:\samp.png");
return img;
}
//calling the function of click event
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
richTextBox1.Text = "Explore any game with Dex";
pictureBox1.Image = load_image();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
NOTE: Handle the exceptions where ever required. Use parameters in function as per requirement
Use PictureBox's Load method in the Form1_Load event. Also make sure the URL is valid.
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Load("https://www.nippon.com/en/ncommon/contents/japan-data/169591/169591.jpg");
}

How to access a variable from button_Click event in windows form application?

I am currently working on a windows form application where I have to store image into local directory and the image into SqlServer database. On the main form, I have used a browse image button which show file dialog on click. Both the image name and path are stored in two separate strings which I have to access from another method that actually stores both the title and image path along with some other data into the database.
I have used the following code on the browse image button.
private void btnBrowseImage_Click(object sender, EventArgs e)
{
string saveDirectory = #"D:\ProductImages\";
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
if(!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
string fileName = Path.GetFileName(fileDialog.FileName);
string fileSavePath = Path.Combine(saveDirectory, fileName);
File.Copy(fileDialog.FileName, fileSavePath, true);
string imgTitle = Path.GetFileName(fileName);
string imgPath = fileSavePath;
}
}
Now, I want to access both the two variables holding the file name and file path respectively from my Add To Database button. I am passing these two variable along with productName, unitPrice and quantity to AddProduct method in my Products call where they will actually be added to the database as illustrated in the btnAddToDatabase_Click event.
private void btnAddToDatabase_Click(object sender, EventArgs e)
{
string productName, unitPrice, quantity, image, imageTitle;
productName = txtProductName.Text.Trim();
unitPrice = txtUnitPrice.Text.Trim();
quantity = txtQuantity.Text.Trim();
image =
imageTitle =
Products.AddProduct(productName, quantity, unitPrice);
FillGrid();
btnClearFields_Click(sender, e);
}
I have tried a lot but no luck as these variables cannot be accessed directly from browse button event so that I can locate them where I want. Is there any way that can help me without any failure?
You need to declare the variables in the class rather than the specific method, then they will have class level scope
public class YourClass
{
private string fileName
private string filePath
private void btnBrowseImage_Click(object sender, EventArgs e)
{
// code here
fileName = Path.GetFileName(fileDialog.FileName);
filePath= Path.Combine(saveDirectory, fileName);
}
private void btnAddToDatabase_Click(object sender, EventArgs e)
{
// code here
fileName = "something";
filePath="something";
}
// other methods
}

Making a background image scale with button size

I'm trying to add some background images to a few buttons in my Win Forms application. The three images are different sizes (ie pixel dimensions don't match, one is 128x128 and another is 256x256). I need the buttons to be identical in size (otherwise the GUI is horribly asymmetrical). Without changing the actual image files, how can I get the images to scale with button size?
I've tried creating my own class, and adding an event handler for the button resize event, but that doesn't seem to work. My code:
class CustomButton : Button {
internal void CustomButton_Resize( object sender, EventArgs e ) {
if ( this.BackgroundImage == null ) {
return;
}
var pic = new Bitmap( this.BackgroundImage, this.Width, this.Height );
this.BackgroundImage = pic;
}
}
and in the form:
this.buttonOne.Resize += new System.EventHandler(this.buttonOne.CustomButton_Resize);
Forgot to mention, the above code does not resize the images at all. The buttons still need to have different sizes to display the images completely.
Easiest way to add a background image to a .NET Button object and scale it to fit
I used this method to avoid any additional coding of new classes and event handlers. This helped me also avoid converting all Button objects into Image objects.
Add image to your Resources.resx file.
Click on your chosen button.
Navigate to the BackgroundImage property and choose the image you imported into the project's resources.resx file.
Navigate to the BackgroundImageLayout property and choose Stretch.
Make sure you don't have anything entered for the Image and Text properties or else they will interfere with your new background image.
The easy programmatic way
Say I have a button btn1, Following code is working perfectly in visual-studio-2010.
private void btn1_Click(object sender, EventArgs e)
{
btn1.Width = 120;
btn1.Height = 100;
}
void btn1_Resize(object sender, EventArgs e)
{
if ( this.BackgroundImage == null )
return;
var bm = new Bitmap(btn1.BackgroundImage, new Size(btn1.Width, btn1.Height));
btn1.BackgroundImage = bm;
}
The better way
You can add eventHandler in the constructor of your custombutton (just to ensure that you are adding eventhandler correctly)
class CustomButton : Button
{
CustomButton()
{
this.Resize += new System.EventHandler(buttonOne.CustomButton_Resize);
}
void CustomButton_Resize( object sender, EventArgs e )
{
if ( this.BackgroundImage == null )
return;
var pic = new Bitmap( this.BackgroundImage, new Size(this.Width, this.Height) );
this.BackgroundImage = pic;
}
}
Now when you will resize the button anywhere your image will get fit(scaled) to its new size.
You could start with something like this...
public class ImageButton : Control
{
public Image backgroundImage;
public Image BackgroundImage
{
get
{
return backgroundImage;
}
set
{
backgroundImage = value;
Refresh();
}
}
public ImageButton()
{
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
if(BackgroundImage != null)
e.Graphics.DrawImage(BackgroundImage, 0, 0, Width, Height);
base.OnPaint(e);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
}
You can just handle paint and draw the image yourself. You may also try using a PictureBox or some other control which has more scaling options

Change button image after clicking it

i have picturebox with picture cb.
PBr1_1.Image = new Bitmap(#"Logos\\Images\\cb.png");
I'd like to change image to cg.png and do some action when i click this image. I was trying something like that but without success:
private void PBr1_1_Click(object sender, EventArgs e)
{
if (PBr1_1.Image.ToString() == "cb.png")
{
PBr1_1.Image = new Bitmap(#"Logos\\Images\\cg.png");
// Do some stuff.
}
}
And then do the same when i click image with cb. To visualise this cb is black circle button image, and cg is green one.
How can i do this?
Jason is right, you should use some kind of temporary storage to save your current bitmap.
The Tag property is useful in this kind of situations. Here a sample code: (Without error handling)
somewhere in your load event
PBr1.Tag = "cb.png";`
PBr1_1.Image = new Bitmap(Path.Combine("Logos\\Images", PBr1.Tag.ToString());
and then in button click
private void PBr1_1_Click(object sender, EventArgs e)
{
string imgPath = "Logos\\Images";
PBr1_1.Image.Dispose();
PBr1_1.Tag = (PBr1_1.Tag == "cb.png" ? "cg.png") : "cb.png") ;
Bitmap bm = new Bitmap(Path.Combine(imgPath, PBr1.Tag.ToString());
PBr1_1.Image = bm;
}
Are you sure that "PBr1_1.Image.ToString()" really returns only the image name?
Maybe you should check this by writing PBr1_1.Image.ToString() to console or something like that

C# Windows Forms: Save & Save As Woes

This is really frustrating me. I'm new to C Sharp so looking for some assistance. My Save/Save As is totally fubar.
Two questions really:
How do I save changes to an existing file without popping a save dialog? If I click save it pops a dialog which is fine so I save it, then make some changes and click Save again it pops a dialog rather than just saving the file to the name already given.
How do I show the filename rather than the full path in the save as dialog? It shows as File Name: C:\Users\username\desktop\save\filename.xml
This is in MainForm.cs.
private void biFileSave_Click(object sender, EventArgs e)
{
// Save diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (!editForm.HasFileName)
{
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
private void biFileSaveAs_Click(object sender, EventArgs e)
{
// Save As diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (editForm.HasFileName)
{
this.saveEditorDialog.FileName = editForm.FileName;
}
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
string strFileName = this.saveEditorDialog.FileName;
}
}
}
This is in EditForm.cs
public string FileName
{
get
{
return this.fileName;
}
set
{
this.fileName = value;
this.Text = Path.GetFileNameWithoutExtension(this.fileName);
}
}
public bool HasFileName
{
get
{
return (this.fileName != null && this.fileName.Length > 0);
}
}
EDIT:
Thank you for helping me on this so quickly! My Save works as expected now, however it introduced a strange issue with Save As (code above).
If I open a file (test.xml) that I have saved, then click Save As (name it test2.xml) it saves to the new file. BUT, when I open that test.xml again and make changes and click Save it saves those changes to the test2.xml. Very strange...any ideas?
Where in code is FileName set? From the sample you've posted, I don't see it being set anywhere, but perhaps it is elsewhere. This may work:
private void biFileSave_Click(object sender, EventArgs e)
{
// Save diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (!editForm.HasFileName)
{
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
editForm.FileName = this.saveEditorDialog.FileName;
}
}
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
1) The Save dialog box will simply return the file path the user wishes to save to. Using this path, you can then perform your save function. If you want to save to the current document, simply skip the dialog box and perform your save function with a cached version of the chosen path.
For example, in your form, have a variable:
string currentFilePath = "";
When the user first opens a Save Dialog Box, fill that variable with the path the user chose.
The next time the user saves (instead of save as), perform a check:
if(!String.IsNullOrEmpty(currentFilePath))
//save method using currentFilePath as the path to save to
2) You need to set the FileName somewhere. You can then use Path.GetFileName on the FileName to get just the name and extension.

Categories

Resources