-1

I'm using this code to save image

 PictureBox1.Image.Save(filePath)

after that I crop image and I want to save it again by replacing the old one with the new cropped one

any help please

regards,,,

Max45
  • 11
  • 1
  • 5

2 Answers2

0

Use the following code when you load the image into the PictureBox instead of the one you are currently using and you'll be fine just saving later. The using statement ensures the file is released once the image is loaded. Replace filePath with your own.

Using stream as new FileStream(filePath, FileMode.Open, FileAccess.Read)
    PictureBox1.Image = Image.FromStream(stream)
End Using

EDIT

From your last comment I can see this code

Try 
    Me.Opacity = 0% 
    Me.PictureBox1.Image = cc() 
    PictureBox1.Image.Save(filePath) 
    source = Image.FromFile(filePath) 
    PictureBox1.Image = source 
    TextBox1.Text = filePath 
    Me.Opacity = 100% 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 

You don't need to reload the image to the PictureBox after saving. Just get rid of the following lines.

source = Image.FromFile(filePath) 
PictureBox1.Image = source 

That should solve your problem at least for now as you won't be saving the image to the same image you load it from (you didn't actually load it). But you will have to find a better solution for your whole algorithm later :)

fnocetti
  • 243
  • 1
  • 9
  • I've tried to do so but I met this error {"The process cannot access the file 'C:\Users\TOSHIBA\Desktop\image20170627083237.png' because it is being used by another process."} – Max45 Jun 27 '17 at 04:33
  • OK this is the code that I am using it and where should I put your code Try Me.Opacity = 0% Me.PictureBox1.Image = cc() PictureBox1.Image.Save(filePath) source = Image.FromFile(filePath) PictureBox1.Image = source TextBox1.Text = filePath Me.Opacity = 100% Catch ex As Exception MsgBox(ex.Message) End Try – Max45 Jun 30 '17 at 00:13
  • What does your cc() function do? – fnocetti Jun 30 '17 at 01:22
  • Private Function cc() As Bitmap Dim s As Screen = Screen.PrimaryScreen Dim img As New Bitmap(s.Bounds.Width, s.Bounds.Height) Dim gr As Graphics = Graphics.FromImage(img) gr.CopyFromScreen(s.Bounds.Location, Point.Empty, s.Bounds.Size) Return img End Function – Max45 Jun 30 '17 at 04:08
  • helooooooooooooooo – Max45 Jul 02 '17 at 06:44
  • Did it work? If yes could you please mark as answered? Thanks! – fnocetti Jul 05 '17 at 01:57
0

This's the answer

Dim bmp1 As New Bitmap(PictureBox1.Image)
        If System.IO.File.Exists(filePath) Then
            System.IO.File.Delete(filePath)
        End If

        bmp1.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg)
        ' Dispose of the image files.
        bmp1.Dispose()
Max45
  • 11
  • 1
  • 5