views:

622

answers:

2

I need to save an image after opening it in from an OFD. This is my code atm:

Dim ofd As New OpenFileDialog
ofd.Multiselect = True
ofd.ShowDialog()


For Each File In ofd.FileNames
   Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.png)
Next

And on the line Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.png) it comes up with the error.

(note: the application will be built on so that's just my first code and it will need to be saved not copied)

+2  A: 

I'd check two things:

  1. That the directory you're saving to exists
  2. That you have write permissions to this directory
Jay Riggs
Well I thought I had checked the directory existed but it didn't Thanks so much, I really hate it though when I spend ages trying to find why it's not working and then knowing it as something ridiculously simple :)
Jonathan
I'm glad you're the only person on the planet that that happens to! :)
Jay Riggs
+3  A: 

Opening or saving an Image puts a lock on the file. Overwriting this file requires you to first call Dispose() on the Image object that holds the lock.

I don't really understand your code but you'd have to do it this way:

    For Each File In ofd.FileNames
        Using img As Image = Image.FromFile(File)
            img.Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.Png)
        End Using
    Next

The Using statement ensures that the img object is disposed and the file lock is released.

Hans Passant