⌘BABAKOV.NET Let's code!
100% [dark] [ru]

How to Open Images in C#

From the archive - might come in handy...
It seems there's nothing simpler than opening an image from disk in C#. But, there are some pitfalls!

Here are two examples.

The first method (incorrect):

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
     Image img = Image.FromFile(openFileDialog1.FileName);
     pictureBox1.Image = img;
}



The second method (correct):

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
fs.Close();
pictureBox1.Image = img;
}



In the first case, if we try to access our image again, we simply cannot do it, this method will not release the file, so it's correct to use the second variant. In the second variant, when accessing the same image file again, no exceptions will occur.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.