I'm trying to use openFileDialog to open a Bitmap image and place it on my form. My form construtor...
public Form1()
{
InitializeComponent();
drawing = new Bitmap(drawingPanel.Width, drawingPanel.Height, drawingPanel.CreateGraphics());
Graphics.FromImage(drawing).Clear(Color.White);
// set default value for line thickness
tbThickness.Text = "5";
}
... opens a new form with a blank screen, and I can draw on it using the mouse and various color selector buttons. I then save the file with this method:
private void btnSave_Click(object sender, EventArgs e)
{
// save drawing
if (file == null) // file is a FileInfo object that I want to use
// to check to see if the file already exists
// I haven't worked that out yet
{
drawing.Save("test.bmp");
//SaveBitmap saveForm = new SaveBitmap();
//saveForm.Show();
}
else
{
drawing.Save(fi.FullName);
}
}
The image does save to the debug folder as a .bmp file. Then I use OpenFileDialog to open the file:
private void btnOpen_Click(object sender, EventArgs e)
{
FileStream myStream;
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "bmp files (*.bmp)|*.bmp";
if (openFile.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = (FileStream)openFile.OpenFile()) != null)
{
using (myStream)
{
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap(openFile.FileName);
this.Controls.Add(picBox);
}
}
}
catch (Exception ex)
{
}
}
}
What happes is that OpenFileDialog box comes up. When I select the file test.bmp, the screen goes away and then reappears, when I select it again, the OpenFileDialog window goes away and I'm back to my form with no image. Was hoping for some pointers. No compile or runtime errors.
Why are you calling ShowDialog() twice?
Just call ShowDialog once, so it doesn't open twice, like you indicated.
From MSDN:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "bmp files (*.bmp)|*.bmp";
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap (myStream);
this.Controls.Add(picBox);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
You open a dialog panel, then when it closes you check to see if the result was OK; then you open another new dialog in the using block; then you assign the image result of that to the PictureBox, and then throw everything away when the using block disposes.
You're calling ShowDialogue twice which is likely the source of your problem. Just use the following code, remove everything else from the method. Your use of using is also incorrect. it does clean up which is disposing of the results. You need to refactor or remove the using statement.
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog()
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox picBox = new PictureBox();
picBox.Location = drawingPanel.Location;
picBox.Size = drawingPanel.Size;
picBox.Image = new Bitmap (dlg.FileName);
this.Controls.Add(picBox);
}
}
}
The code above works but is without clean up or error handling. I'll leave that to you.
Related
I would like to clear a pictureBox after clicking on an 'Encode' button to save it as a new image file in my project. I would like to clear the fields on the form after the user saves the image file.
The code I use to display image on pictureBox:
private void btnOpenfile_Click(object sender, EventArgs e)
{
// open file dialog
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files (*.png)|*.png";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
tbFilepath.Text = open.FileName;
//pictureBox1.ImageLocation = tbFilepath.Text;
}
}
The code I used to clear the pictureBox:
private void clearForm()
{
pictureBox1.Image = null; //doesn't work
pictureBox1.Invalidate(); //doesn't work
tbFilepath.Text = "";
tbMessage.Text = "";
}
I have also tried the following but it did not work either:
private void clearForm()
{
Bitmap bm = new Bitmap(img);
bm.Save(tbFilepath.Text,System.Drawing.Imaging.ImageFormat.Png);
}
I tried using the Refresh() method as one of the commentors suggested, but it did not work either:
private void clearForm()
{
Refresh(); //first attempt
pictureBox1.Refresh();// second attempt
}
I expect the pictureBox field to clear out the existing image I have selected but the image did not clear away.
Before clicking on encode button
After clicking on encode button, the textBox fields are cleared but not the pictureBox field. I used the codes I have added in this question.
Try creating a new Bitmap Variable and use it for the picturebox:
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
pictureBox.Image = bitmap;
pictrueBox.Invalidate();
Also, try to declare a Global Variable for the Bitmap so it is the one to be set as the picture and also the one to be cleared before setting it as the image for the PictureBox.
On the other hand you could try using the OnPaint Method of the Picurebox:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
Bitmap bm = null;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pictureBox1.Image = bm;
}
private void btn_Open_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";
if (ofd.ShowDialog() == DialogResult.OK)
{
bm = new Bitmap(Image.FromFile(ofd.FileName), new Size(pictureBox1.Width, pictureBox1.Height));
textBox1.Text = ofd.FileName;
pictureBox1.Invalidate();
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
bm = null;
pictureBox1.Invalidate();
}
These code I made worked perfectly. So please try it.
How can I set exception for image size? for instance, I am trying to select a file (image) through openfiledialogue but I want to throw an exception if the image size is less than 250x150 (assume).
public void select_image_button17_Click(object sender, EventArgs e)
{
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
AddImagesToButtons(images);
break;
}
}
}
Windows Exceptions is a class used for when the program receive errors that occur during application execution in other words it's for when the programme receive an unusual behavior , for exemple something that will make the programme 'crash' or stop working
Exeptions and validations are 2 different but similar concept
What you are looking for is a validation mechanism and there are many way to do so :
One of the thing you can do is force the image to the desired size this will avoid undesired image size :
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Size = new Size(210, 110);///--add here your desired size
AddImagesToButtons(images);
break;
}
}
}
But if you insist on displaying an error you can use a message box instead ,make a loop and when the desired size is met exit the loop , otherwise display a message Box to the user:
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
bool correctSize=false;
var imageH=null;
var imageW=null
while(!correctSize) //make a loop so only desired size will be taken
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
*ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
if(PictureBox1.Image.Size.Width==yourWidth && PictureBox1.Image.Size.height==yourHeight) //Validate size
{ correctSize =true;
AddImagesToButtons(images);
break;
}
else
MessageBox.Show("Please enter image size your desired size ")
}
}
}
OpenFileDialog is likely concerned with simply selected a file on the file system. Once you've selected, it is up to you to validate that selection meets the criteria, whatever that criteria may be. So once selection is made, and you now know path to the file, use image library to load the file, validate that file loads without issues (remember, may not be a valid file to begin with), and then validate its dimensions. If something doesn't pass, act accordingly, e.g. letting the user know why file is being rejected and suggesting picking a new one.
I have collected a code in c# for browsing files and folders in windows. My sample code segment is as follows:
void ButtonbrowseOnClick(object obj, EventArgs ea)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
But, I am getting the following error:
The name 'openFileDialog1' does not exist in the current context
What's wrong in the code segment?
It does not exist cause it hasn't been defined.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
Are you sure you have defined the openFileDialog1? Changing the second line of your method to the bellow, seems to solve the problem
void ButtonbrowseOnClick(object obj, EventArgs ea)
{
int size = -1;
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //define the variable
DialogResult result = openFileDialog1.ShowDialog();
//your code
I want to keep the last path which is selected. This is the code:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
testParameters.testFileFile = Path.GetFileName(fd.FileName);
testFileLabel.Text = fd.FileName;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
}
to be able to keep the last selected path, I tried to add RestorDirectory and index but I did not get any result:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fd.FilterIndex = 2;
fd.RestoreDirectory = true;
if(...){
...
}
}
then I tried to use "else" instead:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
testParameters.testFileFile = Path.GetFileName(fd.FileName);
testFileLabel.Text = fd.FileName;
}
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
else
{
openFileDialog1.InitialDirectory = #"C:\";
}
}
but again without any result..
Does anyone have any idea?
Editing: Last attemp
private void testFileButton_Click(object sender, EventArgs e)
{
//http://stackoverflow.com/questions/7793158/obtaining-only-the-filename-when-using-openfiledialog-property-filename
OpenFileDialog fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
Environment.CurrentDirectory = #"C:\" ;
if (fd.ShowDialog() == DialogResult.OK )
{
try
{
if (fd.SafeFileName != null)
{
string ffileName = fd.FileName;
testParameters.testFileDir = Path.GetDirectoryName(ffileName);
testParameters.testFileFile = Path.GetFileName(ffileName);
testFileLabel.Text = ffileName;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
}
The documentation states:
true if the dialog box restores the current directory to its original value if
the user changed the directory while searching for files; otherwise, false.
Update: Changing my answer a little, since I think I may have misunderstood your intention:
If I'm not mistaken, your dialog will open to fd.InitialDirectory each time you open it, since that is per definition the default for a new instance of fd. I believe this might be your problem here: You are calling fd = new OpenFileDialog(); each time you are trying to open it.
If you change your code to use the same instance for fd each time (define it in an outer scope, and e.g. access a singleton instance via a Property?), it might remember it's previous directory itself - that is the default behavior (which you can override using the RestoreDirectory property).
Example of getting a singleton instance: This will only instantiate the dialog once, and return the same instance each time you call the property:
Private OpenFileDialog _fd;
private OpenFileDialog SingleFd {
get { return _fd ?? (_fd = new OpenFileDialog()); }
}
// Now in your method, use:
var singleInstance = SingleFd;
You are not using same variable for file dialog everywhere. Like in if block you are showing file dialog fd, but in else part you are using variable openFileDialog. I couldn't understand why you are doing this, or probably it is a typo. Use same variable at both place if you want to set initial directory to "C:\" if user cancels the dialog.
Instead of creating instance in every call, create an instance once and use it for subsequent calls.
Regarding directory restore, if we don't set initial directory, by default it restores the previous directory, even for the different instances.
OpenFileDialog initially uses the current directory which is a process-wide setting. You have overridden this behavior by setting the InitialDirectory. Just don't do that and it will work.
If you want to persist the last directory used across process restarts, capture Environment.CurrentDirectory and save it. Set it before opening the dialog.
Note, that the current directory is a process-wide setting so that different parts of the app can interfere. Also, all relative paths are interpreted relative to this directory (which is why relative path are usually a bug waiting).
string path = #"C:\";
OpenFileDialog fd = new OpenFileDialog();
fd.FileName = "SelectFolder";
fd.InitialDirectory =path;
fd.ValidateNames = false;
fd.CheckFileExists = false;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
string txt1 = System.IO.Path.GetFullPath(fd.FileName),
txt2 = txt1.Replace("SelectFolder", "").Trim();
testFileLabel.Text = txt2.Replace(path, "").Replace(#"\", ""); ;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
The Solution is to set the InitialDirectory path Blank
openFileDialog.InitialDirectory = ""
openFileDialog.RestoreDirectory = True
I am selecting file from openfiledialoge and displaying it in picturebox and its name in textbox when I click on delete button I am getting exception The process cannot access the file because it is being used by another process.
I searched a lot for this exception to get resolved but i didn't fine any of them working, when i tried closing file with imagename which is in textbox i.e the file i am displaying in picturebox ; using IsFileLocked method,this closes and deletes all files of particular directory path ,but how can I delete the only file shown in picturebox,where I am going wrong
public partial class RemoveAds : Form
{
OpenFileDialog ofd = null;
string path = #"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
public RemoveAds()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
ofd = new OpenFileDialog();
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
}
}
else
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
//Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
if (Directory.Exists(path))
{
var directory = new DirectoryInfo(path);
foreach (FileInfo file in directory.GetFiles())
{ if(!IsFileLocked(file))
file.Delete();
}
}
}
public static Boolean IsFileLocked(FileInfo path)
{
FileStream stream = null;
try
{ //Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None );
}
catch (IOException)
{ //the file is unavailable because it is:
//still being written to or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
}
Thanks in advance for any help
The (previously) accepted answer to this question is very poor practice. If you read the documentation on System.Drawing.Bitmap, in particular for the overload that creates a bitmap from a file, you will find :
The file remains locked until the Bitmap is disposed.
in your code you create the bitmap and store it in a local variable but you never dispose of it when you are done. This means your image object has gone out of scope but has not released its lock on the image file you are trying to delete. For all objects that implement IDisposable (like Bitmap) you must dispose of them yourself. See this question for example (or search for others - this is a very important concept!).
To correct the problem properly you simply need to dispose of the image when you are done with it :
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName); // create the bitmap
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose(); // dispose the bitmap object
}
Please do not take the advice in the answer below - you should nearly never need to call GC.Collect and if you need to do it to make things work it should be a very strong signal that you are doing something else wrong.
Also, if you only want to delete the one file (the bitmap you have displayed) your deletion code is wrong and will delete every file in the directory as well (this is just repeating Adel's point). Further, rather than keep a global OpenFileDialog object alive simply to store the file name, I would suggest getting rid of that and saving just the file info :
FileInfo imageFileinfo; //add this
//OpenFileDialog ofd = null; Get rid of this
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
OpenFileDialog ofd = new OpenFileDialog(); //make ofd local
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
imageFileinfo = new FileInfo(ofd.FileName); // save the file name
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose();
}
ofd.Dispose(); //don't forget to dispose it!
}
else
{
return;
}
}
Then in your second button handler you can just delete the one file you are interested in.
private void button2_Click(object sender, EventArgs e)
{
if (!IsFileLocked(imageFileinfo))
{
imageFileinfo.Delete();
}
}
I had the same problem : I loaded a file in a PictureBox and when trying to delete it I got the same exception.
This occurred only when the image was displayed.
I tried them all :
picSelectedPicture.Image.Dispose();
picSelectedPicture.Image = null;
picSelectedPicture.ImageLocation = null;
and still got the same exception.
Then I found this on CodeProject : [c#] delete image which is opened in picturebox.
Instead of using PictureBox.Load() it creates an Image from the file and sets it as PictureBox.Image:
...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
...
private Image GetCopyImage(string path) {
using (Image image = Image.FromFile(path)) {
Bitmap bitmap = new Bitmap(image);
return bitmap;
}
}
No more exceptions when I delete the file.
IMHO, this is the most suitable solution.
EDIT
I forgot to mention that you can safely delete the file immediately after display :
...
// Create image from file and display it in the PictureBox
Image image = GetCopyImage(imagePath);
picSelectedPicture.Image = image;
System.IO.File.Delete(imagePath);
...
use this code
string imgName = ofd.SafeFileName;
if (Directory.Exists(path))
{
var directory = new DirectoryInfo(path);
foreach (FileInfo file in directory.GetFiles())
{
GC.Collect();
GC.WaitForPendingFinalizers();
file.Delete();
}
}
Your button2_Click event handler is cycling through all the files inside your directory & doing the deletes.
You need to change your code like the following:
public partial class RemoveAds : Form
{
OpenFileDialog ofd = null;
string path = #"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
string fullFilePath;
public RemoveAds()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
ofd = new OpenFileDialog();
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
fullFilePath = ofd.FilePath;
ofd.RestoreDirectory = true;
}
}
else
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(fullFilePath);
if(!IsFileLocked(file))
file.Delete();
}
}
public static Boolean IsFileLocked(FileInfo path)
{
FileStream stream = null;
try
{ //Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None );
}
catch (IOException)
{ //the file is unavailable because it is:
//still being written to or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
}
By using GetThumnailImage you have to specify the width and height which is static.
Use the Load method instead.
eg: pictureBox1.Load(Path to the image); by using this u will have no problem in deleting the image or the folder before closing the app. no other methods need to be created.
hope this helps