Friday, March 09, 2007
Load Images with FileStream to Prevent File Locking
Many applications use images. Some applications, the purpose is specifically to manage images. If you are writing a Windows Forms application and loading images you might be tempted to use the easy Image.FromFile(filename). The problem is that FromFile locks the image file until the Image object is destroyed. And, since .NET has non-deterministic garbage collection, you don’t really know when that will be.
Tip: If an image file represents a bad image then .NET throws an OutOfMemoryException. (A terrible exception by the way for this purpose, by the way.)

If you load and Image.FromFile and try to manage it in the file system—for example, by deleting it with in Windows Explorer—you might get the following error.

Instead of using Image.FromFile use Image.FromStream, using a FileStream to load the image, and a MemoryStream to initialize the Image. .NET Won’t lock the file—because you release the lock when you close the FileStream. To incorporate great images like the coliseum below use Image.FromStream as demonstrated.
Tip: If an image file represents a bad image then .NET throws an OutOfMemoryException. (A terrible exception by the way for this purpose, by the way.)

If you load and Image.FromFile and try to manage it in the file system—for example, by deleting it with in Windows Explorer—you might get the following error.

Instead of using Image.FromFile use Image.FromStream, using a FileStream to load the image, and a MemoryStream to initialize the Image. .NET Won’t lock the file—because you release the lock when you close the FileStream. To incorporate great images like the coliseum below use Image.FromStream as demonstrated.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace UsingImage
{
class Program
{
static void Main(string[] args)
{
const string filename =
@"C:\Documents and Settings\paulki01\My Documents" +
@"\My Pictures\Rome\2006_0324Image0149.JPG";
byte[] buffer = null;
using(FileStream fs = new FileStream(filename,
FileMode.Open, FileAccess.Read))
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
}
Image img = Image.FromStream(new MemoryStream(buffer));
using(Form form = new Form())
{
PictureBox pix = new PictureBox();
pix.Parent = form;
pix.Image = img;
pix.SizeMode = PictureBoxSizeMode.StretchImage;
pix.Dock = DockStyle.Fill;
form.TopMost = true;
form.Controls.Add(pix);
form.ShowDialog();
}
}
}
}
Subscribe to Posts [Atom]