Alex Rivera | Logout

Get bitmap file name

Asked 2012-04-07T11:40:49.510
8

I use this line below for create my Bitmap:

Bitmap b = new Bitmap(@"C:\<file name>");

After I modify this bitmap and I want to save it as in line below:

b.Save(@"C:\\<other file name>")

My question is - how to get the file name bitmap from property.
Simply put, I need to save the bitmap with the same name with whom I had initiated it.

Thanks

Edit
Report

2 Answers

8

The upvoted answer is going to get you into trouble. Loading a bitmap from a file puts a lock on the file. You cannot save it back without disposing the bitmap first. Which is a chicken and egg problem which you can't resolve without cloning the bitmap. Which is a bit tricky in itself, the Bitmap.Clone() method is an optimized version that uses the same memory section that put the lock on the file in the first place. So doesn't actually releases the lock.

Here's a little class that takes care of creating a deep clone and memorizes the path and format of the original bitmap:

    class EditableBitmap : IDisposable {
        public EditableBitmap(string filepath) {
            using (var bmp = new Bitmap(filepath)) {
                this.bitmap = new Bitmap(bmp);
                this.bitmap.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
            }
            this.path = System.IO.Path.GetFullPath(filepath);
            this.format = bitmap.RawFormat;
        }

        public Bitmap Bitmap { get { return bitmap; } }

        public void Save() {
            bitmap.Save(path, format);
            this.Dispose();
        }

        public void Dispose() {
            if (bitmap != null) {
                bitmap.Dispose();
                bitmap = null;
            }
        }
        private Bitmap bitmap;
        private System.Drawing.Imaging.ImageFormat format;
        private string path;
    }

And use it like this:

        using (var bmp = new EditableBitmap(@"c:\temp\test.png")) {
            DoSomething(bmp.Bitmap);
            bmp.Save();
        }
answered 2012-04-07T13:03:50.310
0

You do not. Simply. Basically the bitmap does not remember the file -it is your job.

YOu basically tesay "I get a picture send by UPS, after unpacking it - days later - how do I find the shipping number on the picture?" - you don not.

answered 2012-04-07T12:31:44.553

Your Answer