locked
how to save images in picturebox RRS feed

  • Question

  • hi there, i am new to this vb.net. and was just wondering what i have to do to create a save button that actually works. i have a form with a picturebox. i want to create a save button called btnsave and when an image is in the picture box the user can click the save button and it will save it to a location of my choice example c drive. and the other question is how do i get the saved files to name its self in numerical order. for example: image1, image2, image3, image4 and so forth. please help it would be much obliged. thank you very much
    Thursday, May 12, 2011 3:51 PM

Answers

  • Mike Pinto,

    It was for you with sidelines to Mike Feng, :-) confusing yes.

    You have to start this like

     

    In words:

    Save from Picturebox1 the image while you combine the path you get from the foldername and the new created filename plus the extension .jpg (has to be bitmap in both samples, otherwise it needs something more.

     

     'The sample Mike F made and I changed is about jpg, so you have to change that 
    
     PictureBox1.Image.Save(IO.Path.Combine(NewFileName("c:\Rumer\Picture Perfect\Saved Images", "Image"), ".bmp"))

     

     


    Success
    Cor

    • Proposed as answer by Mike Feng Thursday, May 19, 2011 6:01 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Wednesday, May 18, 2011 4:53 PM
  • But in fact is saving from a windows forms picturebox easy.

    http://msdn.microsoft.com/en-us/library/ktx83wah.aspx

    So because image is a property from a picturebox

    dim sfd as new savefiledialog
    if sfd.ShowDialog = dialogresult.OK then
    picturebox1.image.Save(sfd.FileName)
    end if

    Competely done in this message so watch typos.

     

     


    Success
    Cor
    • Proposed as answer by Mike Feng Wednesday, May 18, 2011 8:58 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Thursday, May 12, 2011 5:16 PM
  • Hi Mike P,

    Welcome to the MSDN Forum.

    According to your description, it seems that you want to get the next file name before saveing a image.

    Here is a code snippet for your reference:

      Public Shared Function NewFileName(ByVal path As String, ByVal PrefixName As String) As String
        Dim filename As String = ""
        Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
        Dim num As Integer = 0
        For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
          Dim temp As Integer = 0
          If f.Name.Contains(PrefixName) Then
            If Integer.TryParse(Mid(f.Name, Len(PrefixName) + 1, Len(f.Name) - Len(PrefixName) - Len(f.Extension)), temp) Then
              num = IIf(temp > num, temp, num)
            End If
          End If
        Next
        num = num + 1
        filename = PrefixName & num
        Return filename
      End Function
    

    And you can use this function like this: NewFileName("c:\","Image")

    I hope this will  be helpful.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Proposed as answer by Mike Feng Monday, May 16, 2011 9:12 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Monday, May 16, 2011 9:12 AM
  • Hi Cor,

    THank you for helping the OP out his issue and correct me.

    Thanks.

    I have test your code and found this statement didn't return the expected result: Dim temp = CInt(Val(f.Name)), as you know, the f.name value should be something like this : Image001.jpg, it cannot be converted to a integer munber 1, the variable value will always be 0.

    If I have missed anything, please feel free to let me know.

    Hi Mike Pinto,

    According to your replies, it seems that you didn't call the save method in a correct way, the sample Cor has provided above is the exact code, please just copy and paste, then test it.

    In addtion, as your new requirement of the file name(your orginal name is "Image1" and now is "Image0001"), I have modified my function bellow:

     

     Public Shared Function NewFileName(ByVal path As String, _
       ByVal PrefixName As String) As String
      Dim filename As String = ""
      Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
      Dim num As Integer = 0
      For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
       Dim temp As Integer = 0
       If f.Name.Contains(PrefixName) Then
        If Integer.TryParse(Strings.Right(IO.Path.GetFileNameWithoutExtension(f.Name), _
         f.Name.Length - PrefixName.Length - f.Extension.Length), temp) Then
         num = IIf(temp > num, temp, num)
        End If
       End If
      Next
      num = num + 1
      filename = PrefixName & Format(num, "0000")
      Return filename
     End Function
    
     

     

    please just copy and paste, then test it.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.




    • Edited by Mike Feng Thursday, May 19, 2011 12:45 PM
    • Proposed as answer by Xiong Wei, Jin Friday, May 27, 2011 4:34 PM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Thursday, May 19, 2011 6:33 AM
  • Mike P,

    I never thested the code I gave in this thread, I did this now and saw there where several flaws in it.

    I've corrected it (also in that message) to be sure you don't miss it, I place it here.

    If you use this code the there will always be created an image which goes up 1.

    Option Strict On
    Option Explicit On
    Public Class Form1
     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      PictureBox1.Image = Image.FromFile("C:\Test1\Image.jpg")
      Dim thePath = IO.Path.Combine("c:\Test1\", NewFileName("C:\Test1\", "Image"))
      PictureBox1.Image.Save(thePath, System.Drawing.Imaging.ImageFormat.Jpeg)
     End Sub
     Private Function NewFileName(ByVal path As String, ByVal PrefixName As String) As String
      Dim filename As String = ""
      Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
      Dim num As Integer = -1
      For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
       If f.Name.Contains(PrefixName) Then
        Dim temp = f.Name.ToLower.Replace(PrefixName.ToLower, "")
        temp = temp.ToLower.Replace(".jpg", "")
        Dim tempnum = CInt(Val(temp))
        If tempnum > num Then num = tempnum
       End If
      Next
      Return PrefixName & (num + 1).ToString("0000") & ".jpg"
     End Function
    End Class
    Tested and runs and gives everytime a new number in the image.
    


    Success
    Cor
    • Proposed as answer by Xiong Wei, Jin Friday, May 27, 2011 4:30 PM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:29 AM
    Friday, May 20, 2011 5:47 AM
  • Dim imagename As String = "Image"
      Dim imagenumber As Integer = 1
      Dim fileext As String = Drawing.Imaging.ImageFormat.Jpeg.ToString
      Dim imagesfilename As String = Nothing
      Private Sub Form15_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        imagesfilename = imagename & imagenumber.ToString("0000") & "." & fileext
        Me.Text = imagesfilename
        PictureBox1.Image = New Bitmap("c:/avatar.png")
      End Sub
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        PictureBox1.Image.Save("c:/" & imagesfilename, Drawing.Imaging.ImageFormat.Jpeg)
        imagenumber += 1
        imagesfilename = imagename & imagenumber.ToString("0000") & "." & fileext
        Me.Text = imagesfilename
      End Sub
    

    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    • Proposed as answer by Mike Feng Sunday, May 29, 2011 6:23 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:29 AM
    Friday, May 27, 2011 3:48 PM

All replies

  • And from where do you want to get images? From your hard disc too? So open image from hdd, and save image to hdd (some other position)? Or what did you have in mind?
    Mitja
    Thursday, May 12, 2011 4:08 PM
  • Hi,

    I added some code on our website how you can show an image from disk 

    http://www.vb-tips.com/WPFImageFromDisk.ASPX

    But please one question at a time, replacing an image has to do with files, not with showing.

    For that you need another approach.

     


    Success
    Cor
    Thursday, May 12, 2011 5:03 PM
  • But in fact is saving from a windows forms picturebox easy.

    http://msdn.microsoft.com/en-us/library/ktx83wah.aspx

    So because image is a property from a picturebox

    dim sfd as new savefiledialog
    if sfd.ShowDialog = dialogresult.OK then
    picturebox1.image.Save(sfd.FileName)
    end if

    Competely done in this message so watch typos.

     

     


    Success
    Cor
    • Proposed as answer by Mike Feng Wednesday, May 18, 2011 8:58 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Thursday, May 12, 2011 5:16 PM
  • Hi Mike P,

    Welcome to the MSDN Forum.

    According to your description, it seems that you want to get the next file name before saveing a image.

    Here is a code snippet for your reference:

      Public Shared Function NewFileName(ByVal path As String, ByVal PrefixName As String) As String
        Dim filename As String = ""
        Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
        Dim num As Integer = 0
        For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
          Dim temp As Integer = 0
          If f.Name.Contains(PrefixName) Then
            If Integer.TryParse(Mid(f.Name, Len(PrefixName) + 1, Len(f.Name) - Len(PrefixName) - Len(f.Extension)), temp) Then
              num = IIf(temp > num, temp, num)
            End If
          End If
        Next
        num = num + 1
        filename = PrefixName & num
        Return filename
      End Function
    

    And you can use this function like this: NewFileName("c:\","Image")

    I hope this will  be helpful.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Proposed as answer by Mike Feng Monday, May 16, 2011 9:12 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Monday, May 16, 2011 9:12 AM
  • thanks for all the reply's. i want to save the image in the picturebox so it could be anything from an improted file from c drive to a scanned image which was scanned and sent directly into my picture box, all would be on the hard drive i should imagine. thanks alot
    Tuesday, May 17, 2011 1:43 PM
  • Hi Mike,

    Welcome to Come back.

    Cor has provided a code snippet abhout how to save the image in the picture box and I have provided a code snippet about how to get the name string.

    So please take a look at it.

    Thank you very much.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, May 18, 2011 9:05 AM
  • hi there,

    i have tried cor's code above and it came up with error on image1. so i have wrote out a different code which seems so much simplier to his. which is : 

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnSave.Click

    PictureBox1.Image.Save("c:\Rumer\Picture Perfect\Saved Images\Image0001.bmp" )

    End Sub

    and using your code up the top above mike feng, it does not automatically give the filename with a new number. is this because i have a different piece of code compared to the one above? i would like your help on this anyone. so just to be clear, when i save an image i would like it to be called 'Image0001' and when i save the next one i would like it to be called 'Image0002' and the next to be 'Image3' and so forth. please help!!!! thanks

     
    • Edited by Mike Pinto Wednesday, May 18, 2011 1:59 PM spelling error
    Wednesday, May 18, 2011 1:58 PM
  • hi there,

    i have tried cor's code above and it came up with error on image1. so i have wrote out a different code which seems so much simplier to his. which is : 

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnSave.Click

    PictureBox1.Image.Save("c:\Rumer\Picture Perfect\Saved Images\Image0001.bmp" )

    End Sub


    You did not try my code otherwise you had seen that I use the same code, but than with a safe file dialog instead of a hardcoded file name.

    But there is not even an image1 in my code so from what are you acusing me?

     

    dim sfd as new savefiledialog
    if sfd.ShowDialog = dialogresult.OK then
    picturebox1.image.Save(sfd.FileName)
    end if
    
    

    Success
    Cor
    Wednesday, May 18, 2011 2:17 PM
  • sorry to offend you but i used one of your links then. hows that? didnt mean to offend you or your ego sir. sorry for the confusion, my fault. so do you have any ideas why the code mike feng posted didnt work? i am very basic so dont know the inns and out of codeing. thanks for your time.
    Wednesday, May 18, 2011 2:44 PM
  • I think that Mike (who's first program language was probably C++ or C#) did not took VB programmer behavior (despite his try with the Len and the Mid which I've seen most VB developers avoid currently because is easy fault giving first indexer)

    Most VB developers will do it probably like this

    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        PictureBox1.Image = Image.FromFile("C:\Test1\Image.jpg")
        Dim thePath = IO.Path.Combine("c:\Test1\", NewFileName("C:\Test1\", "Image"))
        PictureBox1.Image.Save(thePath, System.Drawing.Imaging.ImageFormat.Jpeg)
      End Sub
      Private Function NewFileName(ByVal path As String, ByVal PrefixName As String) As String
        Dim filename As String = ""
        Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
        Dim num As Integer = -1
        For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
          If f.Name.Contains(PrefixName) Then
            Dim temp = f.Name.ToLower.Replace(PrefixName.ToLower, "")
            temp = temp.ToLower.Replace(".jpg", "")
            Dim tempnum = CInt(Val(temp))
            If tempnum > num Then num = tempnum
          End If
        Next
        Return PrefixName & (num + 1).ToString("0000") & ".jpg"
      End Function
    End Class
    Tested and runs and gives everytime a new number in the image.

    Try it with this one created based on the code from Mike.Programmers who are used to C languages (C++, Java, JavaScript, C#) use the IIF. 

    VB programmers mostly don't use that, it has different behavior for instance is it not short circuited (this part is for Mike) :-)

    If this runs, than don't forget also to mark the reply from mark as answer, I oversaw that extra question from you.

     


    Success
    Cor



    Wednesday, May 18, 2011 3:12 PM
  • And here is my version. You can open file from hdd (on button click) and save it back (on button click). In both cases you can select paths:

     

    Private fileName As String
    Public Sub New()
    	InitializeComponent()
    	pictureBox1.BorderStyle = BorderStyle.Fixed3D
    End Sub
    
    Private Sub buttonLoad_Click(sender As Object, e As EventArgs)
    	Dim open As New OpenFileDialog()
    	open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp"
    	open.Multiselect = False
    	open.Title = "Image browser"
    	If open.ShowDialog() = DialogResult.OK Then
    		fileName = System.IO.Path.GetFullPath(open.FileName)
    		pictureBox1.Image = New Bitmap(open.FileName)
    		Me.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
    	End If
    End Sub
    
    Private Sub buttonSave_Click(sender As Object, e As EventArgs)
    	Dim dialog As New SaveFileDialog()
    	dialog.Filter = "Save Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg"
    	'show current file name:
    	dialog.FileName = System.IO.Path.GetFileNameWithoutExtension(fileName)
    	'but use can change it anyway:
    	If dialog.ShowDialog() = DialogResult.OK Then
    		Try
    			pictureBox1.Image.Save(dialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
    			MessageBox.Show("Image " & System.IO.Path.GetFileNameWithoutExtension(dialog.FileName) & " saved sucessfully.")
    		Catch ex As Exception
    			MessageBox.Show(ex.Message)
    		End Try
    	End If
    End Sub


    Mitja
    Wednesday, May 18, 2011 3:24 PM
  • hi Cor,

    i have tried the code you supplied and it does not seem to work. i have copy and pasted what you said to do and it does not work. the image still saves. do i have to fill in some bits on your post? like where it says path in brackets. or where it says dim filename as string should i put what i want it to be called? i have tried very quickly and it still didnt work. i am very confused. i use vb.net by the way cor didnt know if you were on about me or mike feng. if anyone knows whats wrong and how to fix it please let me know. thanks for taking your time to help its much obliged. thanks

    Wednesday, May 18, 2011 3:27 PM
  • You have to check if the file already exist if you don't want it to replace it each time you click save.
    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    Wednesday, May 18, 2011 3:38 PM
  • Mike Pinto,

    It was for you with sidelines to Mike Feng, :-) confusing yes.

    You have to start this like

     

    In words:

    Save from Picturebox1 the image while you combine the path you get from the foldername and the new created filename plus the extension .jpg (has to be bitmap in both samples, otherwise it needs something more.

     

     'The sample Mike F made and I changed is about jpg, so you have to change that 
    
     PictureBox1.Image.Save(IO.Path.Combine(NewFileName("c:\Rumer\Picture Perfect\Saved Images", "Image"), ".bmp"))

     

     


    Success
    Cor

    • Proposed as answer by Mike Feng Thursday, May 19, 2011 6:01 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Wednesday, May 18, 2011 4:53 PM
  • Hi Cor,

    THank you for helping the OP out his issue and correct me.

    Thanks.

    I have test your code and found this statement didn't return the expected result: Dim temp = CInt(Val(f.Name)), as you know, the f.name value should be something like this : Image001.jpg, it cannot be converted to a integer munber 1, the variable value will always be 0.

    If I have missed anything, please feel free to let me know.

    Hi Mike Pinto,

    According to your replies, it seems that you didn't call the save method in a correct way, the sample Cor has provided above is the exact code, please just copy and paste, then test it.

    In addtion, as your new requirement of the file name(your orginal name is "Image1" and now is "Image0001"), I have modified my function bellow:

     

     Public Shared Function NewFileName(ByVal path As String, _
       ByVal PrefixName As String) As String
      Dim filename As String = ""
      Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
      Dim num As Integer = 0
      For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
       Dim temp As Integer = 0
       If f.Name.Contains(PrefixName) Then
        If Integer.TryParse(Strings.Right(IO.Path.GetFileNameWithoutExtension(f.Name), _
         f.Name.Length - PrefixName.Length - f.Extension.Length), temp) Then
         num = IIf(temp > num, temp, num)
        End If
       End If
      Next
      num = num + 1
      filename = PrefixName & Format(num, "0000")
      Return filename
     End Function
    
     

     

    please just copy and paste, then test it.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.




    • Edited by Mike Feng Thursday, May 19, 2011 12:45 PM
    • Proposed as answer by Xiong Wei, Jin Friday, May 27, 2011 4:34 PM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:30 AM
    Thursday, May 19, 2011 6:33 AM
  • hi there, i have tried copying and pasting the code mike feng has supplied but it doesnt work. plus i have a blue l,ine underneath: If Integer.TryParse(Right. the line is only on the word right!!!! so i dont know what to do. is it because of the code i have on my save button already? i thought it would be a bit more simplier than this lol. if you do find the answer for me please copuld you do a step by step guide and tell me where to paste what code. thanks for all your help everyone its much obliged. good lads the bunch of you. thanks
    Thursday, May 19, 2011 10:23 AM
  • Hi Mike Pinto,

    The cause is that the method right conflict with the form property. Please change the "Right" to "Strings.Right", and try again.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    Thursday, May 19, 2011 12:45 PM
  • still no luck im affraid :(. it still saves the image but just replaces the image over the top of the old one where as i want it to save as a seperate file which carry's on the number 0001 and saves directly to where the other image does in a folder. thanks
    Thursday, May 19, 2011 1:08 PM
  • I don't know if you have read my reply too. :) Anyway doing a file exists check you can find out whether the file already exist or not and you can allow the user to decide whether to replace or move on.

    If IO.File.Exists(savingpath) Then
                If MessageBox.Show("This file already exist, do you want to replace it?", "File already exist", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(savingpath, Drawing.Imaging.ImageFormat.Jpeg) 'The ImageFormat determine what format you want to save it
                Else
                    MessageBox.Show("No change made", "File not saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
            Else
                MessageBox.Show("File saved please click ok to countinue", "New File saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
                PictureBox1.Image.Save(savingpath, Drawing.Imaging.ImageFormat.Jpeg) 'The ImageFormat determine what format you want to save it
            End If

    Savingpath is the file name and path location. Modify it to fit your particular situation. Hope this will help.
    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    Thursday, May 19, 2011 2:08 PM
  • hi vb study, i did read your post but it is not what i need at this moment in time. i will most probably use that in the future but for now i am stuck with this problem. i have created a save button and made code for it to save the image when i click save. thats fine all well and good but if i wanted to save another file it will just save it over the top where as i want the computer to automatically give it a name which is called 'image02' and on the next save it will be 'image03' and so on. any ideas my friend? thanks for all your help
    Thursday, May 19, 2011 2:15 PM
  • Hi VBStudy,
    
    Thank you for helping the OP out his issue.
    Hi Mike Pinto,
    Now, does my function works fine? what file name do you want to get? "Image1"? "Image01"? "Image0001"?
    I recommand you just add only Cor's code in the save picture subroutine. E.g, 
     
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnSave.Click
     
    PictureBox1.Image.Save(IO.Path.Combine(NewFileName("c:\Rumer\Picture Perfect\Saved Images", "Image"), ".bmp"))
    
    End Sub
    
     I hope this will be helpful.
    Best regards,

    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, May 20, 2011 1:06 AM
  • Mike P,

    I never thested the code I gave in this thread, I did this now and saw there where several flaws in it.

    I've corrected it (also in that message) to be sure you don't miss it, I place it here.

    If you use this code the there will always be created an image which goes up 1.

    Option Strict On
    Option Explicit On
    Public Class Form1
     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      PictureBox1.Image = Image.FromFile("C:\Test1\Image.jpg")
      Dim thePath = IO.Path.Combine("c:\Test1\", NewFileName("C:\Test1\", "Image"))
      PictureBox1.Image.Save(thePath, System.Drawing.Imaging.ImageFormat.Jpeg)
     End Sub
     Private Function NewFileName(ByVal path As String, ByVal PrefixName As String) As String
      Dim filename As String = ""
      Dim dir As IO.DirectoryInfo = IO.Directory.CreateDirectory(path)
      Dim num As Integer = -1
      For Each f As IO.FileInfo In dir.GetFiles("*.jpg")
       If f.Name.Contains(PrefixName) Then
        Dim temp = f.Name.ToLower.Replace(PrefixName.ToLower, "")
        temp = temp.ToLower.Replace(".jpg", "")
        Dim tempnum = CInt(Val(temp))
        If tempnum > num Then num = tempnum
       End If
      Next
      Return PrefixName & (num + 1).ToString("0000") & ".jpg"
     End Function
    End Class
    Tested and runs and gives everytime a new number in the image.
    


    Success
    Cor
    • Proposed as answer by Xiong Wei, Jin Friday, May 27, 2011 4:30 PM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:29 AM
    Friday, May 20, 2011 5:47 AM
  • Hi Mike Pinto

    Try this in a new project: Form1,Button1,Picturebox1,Combobox1,Textbox1

    Make sure you have some images in the MyPictures folder to test, these images will be loaded into the combobox1 for you to select.

    Textbox1 to assign the folder to save the image. in this case I already initialized it to c folder. Don't worry about image get replaced. I include a check condition. if there is already a file name named like image1, you will be asked if you want to replace it or not. My personal experience is not to name image name with Image because I have a digital camera and I think It does that feature of auto increament different picture I take. If I drag these picture in the c folder and if a click of a button is replace my picture I will cry if the pic is something important. :)

    I am new too, my code is very rudimental. I learn by reading different post, search the forum for answers, etc... so far so good. :)

    I learn a lot from Cor, Mike, Bonca and I am still experiment with their code so I can learn new things. (Big Appreciation to ALL)

    Here is the code, I put in some comments to make thing more easy to understand. Hope it will help a little.

    Option Strict On
    
    Public Class Form2
    
      Dim imagenage As String = "Image" 'this is the name of the image that will be saved
      Dim imagenumber As Integer = 1 'the imagenumber will be increamented to give the filename a progressive increamented name
      Dim imagefileext As String = Drawing.Imaging.ImageFormat.Jpeg.ToString 'don't forget the extension in this case Jpeg
      Dim imagesfilename As String = Nothing 'this is the filename that the image will be saved with.
      Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'initialize the textbox1.text used for the location where to save the image
        TextBox1.Text = "c:/"
    
        'pre load the combobox with image files from mypictures forlder
        For Each imagefile As String In My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyPictures, FileIO.SearchOption.SearchTopLevelOnly, "*.Jpeg*", "*.jpg*")
          Me.ComboBox1.Items.Add(imagefile)
        Next
        ComboBox1.SelectedItem = ComboBox1.Items(0)
        'load an image to the picturebox
        PictureBox1.Image = New Bitmap(ComboBox1.SelectedItem.ToString)
        'This will stretch the image to fit the picturebox size
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    
        'show the filename that the image will be saved with to the user
        imagesfilename = imagenage & CStr(imagenumber) & "." & imagefileext
        Me.Text = imagesfilename
    
    
    
      End Sub
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'folder where to save the image
        Dim saveinfolder As String = TextBox1.Text
    
        'form the saving path
        Dim savingpath As String = saveinfolder & imagesfilename
    
        'do the actual save and give option to the user to choise and inform the action taken
        If IO.File.Exists(savingpath) Then
          If MessageBox.Show("This file already exist, do you want to replace it?", "File already exist", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) = Windows.Forms.DialogResult.OK Then
            PictureBox1.Image.Save(savingpath, Drawing.Imaging.ImageFormat.Jpeg) 'The ImageFormat determine what format you want to save it
          Else
            MessageBox.Show("No change made", "File not saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
          End If
        Else
          MessageBox.Show("File saved please click ok to countinue", "New File saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
          PictureBox1.Image.Save(savingpath, Drawing.Imaging.ImageFormat.Jpeg) 'The ImageFormat determine what format you want to save it
        End If
    
        'increase the image number <<======
        imagenumber += 1
    
        'show the next filename the new image will be saved with
        imagesfilename = imagenage & CStr(imagenumber) & "." & imagefileext
        Me.Text = imagesfilename
      End Sub
    
      'each time the user select a image from the combobox the image will be displayed in the picturebox
      Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        PictureBox1.Image = New Bitmap(ComboBox1.SelectedItem.ToString)
      End Sub
    End Class
    
    What it does is save image in the picture box to the C folder with filename Image1, Image2, Image3 and so on...
    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    • Proposed as answer by Mike Feng Wednesday, May 25, 2011 1:45 PM
    • Unproposed as answer by Mike Pinto Friday, May 27, 2011 10:03 AM
    Saturday, May 21, 2011 12:07 AM
  • hi cor, i have gave your code a go but it does not seem to work i think the reason why is that i have ez twain. and that is used to help my program find any twain scanner. so i can scan fr om it. any way i have some blue lines underneath finding the scanner button which is ( select source) so i have been fiddling around with it and cant get it to work. thanks for your help though. im sure it would have worked if that wasnt in there. i will be trying the other posts shortly sorry about the time it takes to get back to you as i am very busy at work at the min. and this project is just for spare time. thanks alot guys.

     

    Tuesday, May 24, 2011 8:33 AM
  • Hi Mike P,

    Ok, I  look forward you and tell us how about VbStudy's solution.

    Best regards,


    Mike Feng [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, May 25, 2011 1:47 PM
  • hello there vb study. i thank you all for your hard work on trying to help me round this problem. sorry for the late reply as i have been out the country for a few days so haven't had chance to test it untill now. i have tried your code but it comes up with an error with trying to load the form to do the test run.

    ComboBox1.SelectedItem = ComboBox1.Items(0) = it says argument out of range exception was unhandled.

    i dont know what that means. but anyway the way you describe it in your post it asks for where you want to save the image each time where as i would like it just to save automatically to an area which i decide with in the code.i just want one button which i have already created which is called btnsave, to save the image to the destination when i click it. after we get this porblem out of the way i am going to create another button called save as, but for the time being i just want a normal save button. would you all please carry on what your doind in trying to help me. thanks alot mike pinto. much obliged

    Friday, May 27, 2011 10:03 AM
  • I Mike Pinto

    I think the Argument out of range exception was unhandled is probably caused because the code is trying to load image files of type Jpeg and Jpg from the MyPictures folder and if there are no that kind of files the combobox is not getting filled up. So when the reference made to the index 0, there was nothing there so the exception get raised.

    Comment that part out

    'pre load the combobox with image files from mypictures forlder
            'For Each imagefile As String In My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyPictures, FileIO.SearchOption.SearchTopLevelOnly, "*.Jpeg*", "*.jpg*")
            '    Me.ComboBox1.Items.Add(imagefile)
            'Next

    and change it with this

    Dim imagefolderfrom As New FolderBrowserDialog
        If imagefolderfrom.ShowDialog = Windows.Forms.DialogResult.OK Then
          For Each imagefile As String In My.Computer.FileSystem.GetFiles(imagefolderfrom.SelectedPath, FileIO.SearchOption.SearchTopLevelOnly, "*.Jpeg", "*.jpg", "*.bmp", "*.png")
            Me.ComboBox1.Items.Add(imagefile)
          Next
        Else
          Me.Text = "No image loaded"
          Exit Sub
        End If
    

    What this part of code does is show you a browsing dialog for you to choise what folder to get the images. Now make sure you select a folder that there are images in it. The code will look for image file type Jpeg,Jpg,Bmp,Png and load them in the combobox. If you canel from the dialog then No image loaded will be display on the window title and exit the sub without going any further. So only when there are image loaded, it will move on to the Combobox1.SelectedItem line. We can also use a Try Catch, but I think for now is better to focus on your original question. So try this varietion and let me know what happen. and Thank you for taking time to test my code. Appreciate that.

    I studied Mike's code. I think when you understand all this we will probably end up usign his code. It is very exciting to see just a few line does so much. :)


    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    Friday, May 27, 2011 2:43 PM
  • hi there, i hate to be a pain in the back side but i do not want a combo box, a text box and so forth,  all i want is one button, that when you click it,  it saves the image. which i have already created which is fine but with the same button i want it to carry on the name and number of the image name. for example:

    picture0001, picture0002, picture0003 and so forth. i think having all the other bits like combo box and text box does not make the form look nice. here is my code for the save button already.

     

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

    btnSave.Click

    PictureBox1.Image.Save(

    "c:\Rumer\Picture Perfect\Saved Images\Image0001.jpg"

    )

     

    End

    Sub

    so i would like a bit of code that carry's on the number each time i want to save an image. thanks for your help so far. mike pinto

     

    Friday, May 27, 2011 3:02 PM
  • Dim imagename As String = "Image"
      Dim imagenumber As Integer = 1
      Dim fileext As String = Drawing.Imaging.ImageFormat.Jpeg.ToString
      Dim imagesfilename As String = Nothing
      Private Sub Form15_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        imagesfilename = imagename & imagenumber.ToString("0000") & "." & fileext
        Me.Text = imagesfilename
        PictureBox1.Image = New Bitmap("c:/avatar.png")
      End Sub
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        PictureBox1.Image.Save("c:/" & imagesfilename, Drawing.Imaging.ImageFormat.Jpeg)
        imagenumber += 1
        imagesfilename = imagename & imagenumber.ToString("0000") & "." & fileext
        Me.Text = imagesfilename
      End Sub
    

    Be a good forum member. Make this forum a great place to meet and interact with others around the world.
    • Proposed as answer by Mike Feng Sunday, May 29, 2011 6:23 AM
    • Marked as answer by Mike Feng Thursday, June 2, 2011 9:29 AM
    Friday, May 27, 2011 3:48 PM
  • Hi Mitja,

    while using your code for saving picture box to image file, I am getting an error message "Object reference not set to an instance of an Object"

    Please suggest what to do?

    It will be very helpful.

    regards

    sachin

    Saturday, February 24, 2018 3:26 AM