Click here to Skip to main content
16,019,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Goodmorning.

Is there anyone know how to replace an image in a folder?
because when im trying this, I get an error "A Generic Error Occured in GDI+"

Here is my process:
*First I load the image in a picture box, so that the user can see the current picture
VB
If M_FilePath = Nothing Then
           Else
               PictureBox2.Image = Nothing
                PictureBox2.Image = Image.FromFile(M_FilePath)
           End If


*and browse a new picture
VB
Dim OD As New OpenFileDialog

       With OD
           If .ShowDialog = Windows.Forms.DialogResult.OK Then
               PictureBox2.Image = Nothing
               PictureBox2.Image = Image.FromFile(.FileName)
           End If
       End With




*Then, I want to update the new picture i browsed.
PictureBox2.Image.Save(Application.StartupPath + "\ITEM\" + txtItemCode.Text.Trim + ".jpg")


but still i got the error.
Any Suggestions will be so much appreciated. Thank you so much in advance.
Posted
Comments
Sergey Alexandrovich Kryukov 7-Nov-13 21:52pm    
In what line?
Note, the whole idea to replace a file looks suspicious. Why?
—SA

1 solution

This doesn't really make any sense, but a big problem is that you're using Image.FromFile. This will keep the file locked for the lifetime of the Image object and prevent you from writing new file content to it. In order to get around this, you have to create a FileStream object and pass that to Image.FromStream. Then you can close the FileStream and then write to the file any way you want.

Examples...[^]
 
Share this answer
 
Comments
Member 8076338 10-Nov-13 20:31pm    
Goodmorning sir, I try also this code. but still i got the same error.

PictureBox2.Image = Nothing
Dim FileStream1 As New System.IO.FileStream(M_FilePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim MyImage As Image = Image.FromStream(FileStream1)
PictureBox2.Image = MyImage


did i miss anything? thank you so much,
Dave Kreskowiak 10-Nov-13 20:35pm    
The code you posted doesn't close the file when you're done reading it.

On top of that, do you know if the file is a valid format??
Member 8076338 10-Nov-13 20:54pm    
Goodmorning sir, I can now replace the image in a specific folder, thank you also for the link. This is what I did.

Dim mypic As New System.IO.FileStream(M_FilePath, IO.FileMode.Open)
Dim img As Image = Image.FromStream(mypic)
mypic.Close()
PictureBox2.Image = img

Thank you, God Bless.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900