C#, .NET 2.0, XP+Latest updates
I am reading an image from a database into 'rawData'. I then use
the following code to create an Image and add it to my cache:
// Variables used..
// SortedList<string, Image> m_images;
// string fileName;
// string imageId;
// byte[] rawData;
// 'File' is System.IO.File
// Save it to a file
File.WriteAllBytes(fileName, rawData);
// Add the image to the cache
m_images.Add(imageId, Image.FromFile(fileName));
// Delete the file
File.Delete(fileName);
The problem is that the File.Delete(...) is thowing an IOException,
complaining the file 'fileName' is in use by another process. It
seems the Image.FromFile(...) is leaving the file open (It's not the
WriteAllBytes(...). Does the Image rely on the file always being
present I assumed the Image was 'in memory'. Is there some
'parallel' (multithread) processing going on here
Alternatively, is there an better way that I can create the Image from the 'rawData' without the intermediate file
Thank you
Rob

Creating Images
oliver.lauta
The other option:
Image fileImage = Image.FromFile(fileName);
Image memoryImage = new Image(fileImage); // Fails to compile
Cannot create an instance of the abstract class or interface 'System.Drawing.Image'
Jay Longenderfer
Try
Bitmap fileImage = Bitmap.FromFile(fileName) as Bitmap;
Bitmap memoryImage = new Bitmap(fileImage);
It's my recollection that the Bitmap cast is required, I may be wrong.
quadcell
*grin* yeah, I should have thought of that as well. But, what we've discussed is good to know, it can be a real bear. If a bitmap is read from a file, that file stays locked for the lifetime of the Bitmap object.
Of course, no matter what happens, you should call Dispose on the memoryImage as well, once you're done with it. If you get into a habit of calling Dispose on any object that offers it when you're finished with it, you'll run into this sort of problem a lot less often :-)
sweens319
// Save it to a file
File.WriteAllBytes(fileName, rawData);
// Create an image from the file
Bitmap fileImage = Image.FromFile(fileName) as Bitmap;
// Create an in-memory image and free the file image
Image memoryImage = new Bitmap(fileImage);
fileImage.Dispose();
// Add the image to the cache
m_images.Add(imageId, memoryImage);
// Delete the file
File.Delete(fileName);
But of course, now you have me looking at the Bitmap() constructor that has a paremeter of the 'actual pixel data' (my rawData), meaning the file may not be necessary!
Dan.Dittenhafer
You need to make an in memory copy of that image, and then you can delete it. The image keeps a file lock.
I believe that
Image b1 = Image.FromFile(fileName);
Image b2 = new Image(b1);
b1.Dispose();
will do it.
If not, then Image b2 = b1.Clone() as Image;
may do the trick, I do recall one of those methods ( I think the Clone ) copies the file handle as well.