To clear loaded images in a picturebox-c# - c#

Initially I will be loading images(say 20 images) into a picturebox from a specified folder through selection from combobox dropdown, they get loaded normally into the picturebox.
The problem I am facing is when I select the next folder to acquire the image for processing, the previously selected folders images are also displayed in the picturebox after its count only the next folders images are displayed, I am unable to clear the previously loaded images.
To be specific, when I click on a folder from dropdown I want the particular folders image inside the picturebox I don't want the previously loaded images along with them. Am working in VS2013 with c#.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ArrayList alist = new ArrayList();
int i = 0;
int filelength = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(#"C:\Users\Arun\Desktop\scanned");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
}
private void button7_Click(object sender, EventArgs e)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void button8_Click(object sender, EventArgs e)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1;
}
private void button9_Click(object sender, EventArgs e)
{
string selected1 = comboBox1.SelectedItem.ToString();
string selected2 = comboBox2.SelectedItem.ToString();
//Initially load all your image files into the array list when form load first time
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected1, selected2)); //Source image folder path
try
{
if ((inputDir.Exists))
{
//Get Each files
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if (file.Extension == ".tif")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
else if(file.Extension == ".jpg")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
}
pictureBox1.Image = Image.FromFile(alist[0].ToString()); //Display intially first image in picture box as sero index file path
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = 0;
}
}
catch (Exception ex)
{
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
else if(e.KeyCode == Keys.A)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Your code has many issues.
The one you are looking for is that you don't clear the alist before loading new file names.
So insert:
alist.Clear();
before
//Get Each files
And also
filelength = alist.Count;
after the loop. No need to count while adding!
Also note that ArrayList is pretty much depracated and you should use the type-safe and powerful List<T> instead:
List<string> alist = new List<string>();
Of course a class variable named i is silly and you are also relying on always having a SelectedItem in the comboBox2.
And since you are not properly Disposing of the Image you are leaking GDI resources.
You can use this function for properly loading images:
void loadImage(PictureBox pbox, string file)
{
if (pbox.Image != null)
{
var dummy = pbox.Image;
pbox.Image = null;
dummy.Dispose();
}
if (File.Exists(file)) pbox.Image = Image.FromFile(file);
}
It first creates a reference to the Image, then clears the PictureBox's reference, then uses the reference to Dispose of the Image and finally tries to load the new one.

Related

How to get the picturebox image path that captured by the webcam

In my form. I have two picturebox and a button that capture the image into picturebox.
Two Picturebox
WebcamImage - represent the live camera image
PreviewImage - represent the Captured image from webcamimage
When i saved this captured image it will go to my UserImage picturebox (In my Usercontrol)
The problems is i don't know how i'm gonna get the picturebox image path.
What i want is when i click my saved button the image path will be saved to my label text.
Here's my code
PS: I'm using Aforge.dll
public partial class CaptureImage : Form
{
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
RegisterCustomer _view;
public CaptureImage(RegisterCustomer view)
{
InitializeComponent();
this._view = view;
}
private void CaptureImage_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
if (FinalFrame.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < FinalFrame.VideoCapabilities.Length; i++)
{
if (FinalFrame.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = FinalFrame.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
}
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
btn_save.Hide();
btn_cancel.Hide();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
WebcamImage.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void CaptureImage_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btn_save_Click(object sender, EventArgs e)
{
_view.UserImage.Image = PreviewImage.Image;
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_capture_Click(object sender, EventArgs e)
{
PreviewImage.Image = (Bitmap)WebcamImage.Image.Clone();
PreviewImage.BringToFront();
btn_capture.Hide();
btn_save.Show();
btn_cancel.Show();
}
}
This is only i know in getting the picturebox image path by using openfile dialog
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}

Showing images into a list view

I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.
private void btnZoom_Click(object sender, EventArgs e)
{
ImageList imgs = new ImageList();
imgs.ImageSize = new Size(100, 100);
string[] paths = { };
paths = Directory.GetFiles("TestFolder");
try
{
foreach (string path in paths)
{
imgs.Images.Add(Image.FromFile(path));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listView1.SmallImageList = imgs;
listView1.Items.Add("2",0);
}
To get all the image files you can do
IEnumerable<string> paths = Directory.GetFiles(#"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in
then you can just iterate thru the list to add them in
Here is the working code:
and the code is :
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles( "pics//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
foreach (string pic in pics)
{
imageList1.Images.Add(Image.FromFile(pic));
}
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
}
}
and at designer set this:

I have a query about checked list boxes in c#

I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?

Save file dialog An unhandled exception

I have some problems about savefiledialog c#, I have an unhandled exception of type System.NullReferenceException when I debug, this's code:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
switch (fileName)
{
case "":
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
}
here is my declare:
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
here is my full code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Bitmap
//Graphics
Graphics g;
Pen p = new Pen(Color.Black, 8);
Point start = new Point(0, 0);
Point end = new Point(0, 0);
bool drawing = false;
//private int x1;
//private int x2;
//private int y1;
//private int y2;
//private int d1;
//private int d2;
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
private Size fullSize;
private void btnColorPicker_Click(object sender, EventArgs e)
{
//Get colors from colordialog
DialogResult r = colorDialog1.ShowDialog();
if (r == DialogResult.OK)
{
p.Color = colorDialog1.Color;
}
}
private void PanelDrawing_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void PanelDrawing_MouseMove(object sender, MouseEventArgs e)
{
if (drawing && !earaser)
{
p.Width = PenSize.Value;
p.Color = colorDialog1.Color;
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.HSplit;
}
else if (drawing && earaser)
{
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.Cross;
}
else if (!drawing)
{
PanelDrawing.Cursor = Cursors.Default;
}
start = end;
}
private void PanelDrawing_MouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
if (e.Button == MouseButtons.Left)
{
drawing = true;
}
}
private void PenSize_Scroll(object sender, EventArgs e)
{
p.Width = PenSize.Value;
label1.Text = "" + PenSize.Value;
}
bool earaser = false;
private void btnEaraser_Click(object sender, EventArgs e)
{
p.Color = Color.White;
p.Width = 10;
earaser = true;
}
private void btnBrush_Click(object sender, EventArgs e)
{
earaser = false;
}
private void btnClear_Click(object sender, EventArgs e)
{
g.Clear(PanelDrawing.BackColor);
}
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
private void Form1_Load(object sender, EventArgs e)
{
fullSize = SystemInformation.PrimaryMonitorMaximizedWindowSize;
bitmap = new Bitmap(fullSize.Width, fullSize.Height);
g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(BackColor);
}
}
probably it didn't catch the variable if its null or an empty string.
so instead of using switch statement, try doing it in If-Else statement.
This isn't the place to use a switch statement. This is much easier re-written as an if:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
The switch isn't appropriate just because its extremely confusing, and you have to test for multiple cases (null, empty string, whitespace). You can jam the code and make it work, but this is a lot more fool-proof.
Without seeing the rest of your code, its impossible to tell whether bitmap is going to be null or not. If its null, then calling .Save will result in a NullReferenceException. The best way to know why its null is to learn how to use the debugger. Set a breakpoint at the bitmap or where you utilize the bitmap to see why you aren't writing to it or creating the object in the first place.
Since you haven't specified "where" the System.NullReferenceException is taking place. I will assume the following 2 cases
1.fileName is null. If that's the case add 1 more case (as shown below ) to your switch statement that takes null into consideration.
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
2. You are using the same image stream, while saving, which was used to construct it. If that's the case use a new bitmap object as shown below.
var newBitmap = new Bitmap(bitmap);
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
newBitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
newBitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
Firstly, switch is not good way to handle strings I think.
string.IsNullorEmpty and string.IsNullorWhiteSpace might be useful for you.
Can you trace bitmap on your console? Are you sure you declared and initialized it correctly in your code?
This should solve any possibility:
private void saveToolStripMenuItem_Click(object sender,System.EventArgs e)
{
var _Bitmap = new Bitmap(bitmap);
//when we quit here we don't need this anymore; declaring it here helps with memory management
if(_Bitmap == null)
return;
if(string.IsNullorEmpty(fileName)||string.IsNullorWhiteSpace(fileName)
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
}
else
{
_Bitmap.Save(fileName,ImageFormat.Bmp);
}
}
You assign bitmap on Form1_Load, try to do it on separate method and call it when you need it.

Flickering image after loading in winforms at timer tick event

My question is the following:
I have a timer and each 1 ms i want to load an image and display it in a picture box in win forms
The first images work very fine however from some point the images start loading hard.
Can you please tell me how to solve this problem?
Regards and thank you for your time :)
private string path = "";
private int index = 0;
private void fileSourceToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
path = fullPath.Replace(fileName, "");
MessageBox.Show("Path for file source has been selected");
}
}
private const string IMAGENAME = "TestImage";
Bitmap b;
private void timer_Tick(object sender, EventArgs e)
{
try
{
string currentImage = IMAGENAME + index.ToString() + ".bmp";
index++;
b = new Bitmap(path + "\\" + currentImage);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Image = b;
}
catch { };
}
private void button1_Click(object sender, EventArgs e)
{
timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
timer.Stop();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
string currentImage = IMAGENAME + index.ToString() + ".bmp";
index += 1;
Bitmap b = new Bitmap(path + "\\" + currentImage);
pb.Image = b;
}
catch { };
}
private void button4_Click(object sender, EventArgs e)
{
try
{
index -= 1;
string currentImage = IMAGENAME + index.ToString() + ".bmp";
Bitmap b = new Bitmap(path + "\\" + currentImage);
pb.Image = b;
}
catch { };
}
Play with DoubleBuffered property first.
GDI+ is very slow and even when using double buffering then it's still slow.
I would suggest you to find an alternative as there isn't really a way to fix the "flickering".
However there is one thing, the way you're actually loading the images in the tick handle is pretty cpu consuming.
I would suggest you load all the required image's bytes into a collection of some sort, ex. an array.
Then simply create the bitmap from the image bytes.
Besides you're not even disposing the current image, which you should before allocating new memory for the next image.

Categories

Resources