PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2010 How Can I save a picture as a JPEG file? I NEED HELP!!-VBForums
Results 1 to 15 of 15

Thread: How Can I save a picture as a JPEG file? I NEED HELP!!

  1. #1

    Thread Starter
    New Member
    Join Date
    May 2012
    Posts
    14

    Question How Can I save a picture as a JPEG file? I NEED HELP!!

    What I want to do:
    I want the user to click on the picture box, an openfiledialog box open, the user choose a photo from a file on their computer, and that picture load in the picture box. Then I want the user the click on a button and a savefiledialog pop up. from there i want the user to be able to type a name and click ok and the picture save as a jpeg, to a file that i specify, to later be opened in another form.
    I've got the loading part good. that works fine. I just cant figure out how to save the image that has been
    loaded into the picture box. Right now for testing purposes, I have a form with a picturebox, a button, and a savefiledialog on it, with default names.

    What I've tried (the numbers after each method corresponds with the errors i got):
    the first three were done inside "if savefiledialog1.showdialog() = dialogresult.ok then"
    option1
    Me.PictureBox1.Image.Save(Application.StartupPath & "\gallery\") (1)

    option2
    PictureBox1.Image.Save(Application.StartupPath & "\gallery\") (1)

    option3
    PictureBox1.Image.Save(SaveFileDialog1.FileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg) (1)

    option4
    with this one i just typed it into the buttons click event.
    SaveFileDialog1.InitialDirectory = (Application.StartupPath & "\gallery\")
    SaveFileDialog1.FileName = "New Entry"
    SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"
    SaveFileDialog1.ShowDialog()
    Dim w As New IO.StreamWriter(SaveFileDialog1.FileName)
    w.Write(PictureBox1.Image)
    w.Close() (3)

    When i try this one it saves the image as a .bmp, but when i try to open it in paint, i get this windows error: paint cannot read this file. This is not a valid bitmap file or its format is not currently supported.
    and when i try to load the saved image into the picturebox (as the user would), i get this error: ArgumentException was unhandled.
    parameter is not valid

    option5
    Dim saveFileDialog1 As New SaveFileDialog()
    saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"
    saveFileDialog1.Title = "Save an Image File"
    saveFileDialog1.ShowDialog()
    If saveFileDialog1.FileName <> "" Then
    Dim fs As System.IO.FileStream = CType _
    (saveFileDialog1.OpenFile(), System.IO.FileStream)
    Select Case saveFileDialog1.FilterIndex
    Case 1
    Me.PictureBox1.Image.Save(fs, _
    System.Drawing.Imaging.ImageFormat.Jpeg) (1)
    Case 2
    Me.PictureBox1.Image.Save(fs, _
    System.Drawing.Imaging.ImageFormat.Bmp)
    Case 3
    Me.PictureBox1.Image.Save(fs, _
    System.Drawing.Imaging.ImageFormat.Gif)
    End Select

    fs.Close()
    End If

    option6
    Dim image As image = PictureBox1.Image (2)
    image.Save("C:\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)



    Errors I've got:

    (1) A generic error occured in GDI+

    (2) Value of type 'System.Drawing.Image' cannot be converted to 'WindowsApplication1.Image'

    (3) ArgumentException was unhandled
    parameter is not valid

    What am I doing wrong? Is there something I'm missing? Another way I should do this? I've also tried using a button, panel, and a retangle shape instead of a picturebox with no luck. I tried using the backgroundimage property instead of the image prop with no luck. I read somewhere not to use the .load but instead use .fromfile..... again no luck. so I am completely stummped. I've thought about trying to convert the image to bmp since it seems easier to save a bmp, but i really would like the image to be saved as a jpeg. Im using visual basic 2010 express and if anyone could please help me out, I would be most greatful. Thank you and someone please please please help me!!

    sorry this was so long. I just wanted to make sure im totally clear on what im trying to accomplish and what i've done so i hopefully get the help i need. Thanks all!!

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Option 3 is the correct way to save an image.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  3. #3
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,242

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Error 1: you cannot overwrite an existing file from Picturebox (or bitmap, for that matter). You have to create an entirely new file. Don't use the SaveFileDialog!

    Error 2: self-evident. A PictureBox image has a unique format so you can't declare it as anything different to what it is!

    Error 3: you can't stream a PictureBox image in this way. It has it's own streaming protocol.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  4. #4
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,894

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    I don't know if this will help but this is some code I wrote a while back in VB2005 which takes an image then saves a resized version of it and a thumbnail version of it then deletes the original image.

    Code:
    Try
                        PicFileName = aPicLog(x) 'TempFolder & "\" & listview2.Items(x).Text
                        If Mid(PicFileName, 1, 1) = Chr(10) Then PicFileName = Mid(PicFileName, 2)
                        Dim MySourceImage As New Bitmap(PicFileName)
    
                        HolderImage = Imager.ResizeImage(MySourceImage, PicWidth, PicHeight)
                        NewPicture = txtItem.Text & "_" & PhotoIndexer.ToString.PadLeft(3, "0") & ".Jpg"
                        HolderImage.Save(OutPutFolder & "\" & txtAuction.Text & "\" & NewPicture, System.Drawing.Imaging.ImageFormat.Jpeg)
                        HolderImage = Imager.ResizeImage(MySourceImage, ThumbWidth, ThumbHeight)
                        NewThumb = txtItem.Text & "_" & PhotoIndexer.ToString.PadLeft(3, "0") & "t.Jpg"
                        HolderImage.Save(OutPutFolder & "\" & txtAuction.Text & "\" & NewThumb, System.Drawing.Imaging.ImageFormat.Jpeg)
                        PhotoIndexer = PhotoIndexer + 1
                        MySourceImage.Dispose()
                        HolderImage.Dispose()
                        System.IO.File.Delete(PicFileName)
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try

  5. #5
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,589

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    There can be other reasons too but the most common reason that I've seen for getting the error message about a generic error in GDI+ is trying to save an Image object created from a file where the FileStream has been closed. For instance, if you call the Load method of the PictureBox to load an image file and then call Save on the Image you will get the error.

    If you want to save the Image again afterwards then call Iamge.FromFile to create the Image and assign it directly to the Image property of the PictureBox. This creates a dilemma though, because you have to Dispose the Image to unlock the file but you have to Save the Image before you Dispose it, so you can't Save it to the same file path. What you need to do is Save the Image to a temp file, Dispose the Image and then move the temp file to the original location and overwrite the original file.

  6. #6
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Quote Originally Posted by jmcilhinney View Post
    There can be other reasons too but the most common reason that I've seen for getting the error message about a generic error in GDI+ is trying to save an Image object created from a file where the FileStream has been closed. For instance, if you call the Load method of the PictureBox to load an image file and then call Save on the Image you will get the error.

    If you want to save the Image again afterwards then call Iamge.FromFile to create the Image and assign it directly to the Image property of the PictureBox. This creates a dilemma though, because you have to Dispose the Image to unlock the file but you have to Save the Image before you Dispose it, so you can't Save it to the same file path. What you need to do is Save the Image to a temp file, Dispose the Image and then move the temp file to the original location and overwrite the original file.
    You can save yourself all that trouble by loading an image using a method like this:-
    vbnet Code:
    1. '
    2.     Private Function LoadImage(ByVal path As String) As Bitmap
    3.  
    4.         Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read)
    5.         Dim fileData As Byte() = New Byte(fs.Length - 1) {}
    6.  
    7.         fs.Read(fileData, 0, fileData.Length)
    8.         fs.Close()
    9.  
    10.  
    11.         Return Bitmap.FromStream(New MemoryStream(fileData))
    12.     End Function
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  7. #7
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    If you like succinctness, you can compact it like:-
    vbnet Code:
    1. Dim bmp As Bitmap = Bitmap.FromStream(New MemoryStream(File.ReadAllBytes("c:\ava.png")))

    I will state though that MS shouldn't have to require us to do this. Its not natural(at least to me) to expect that the Bitmap will own the stream if it was created using it, specifically because a Bitmap doesn't require a backing Stream in any other circumstance.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,589

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    One issue you have there, in both cases, is that you have a MemoryStream to which you retain no reference, so you can never dispose it. Because there's no reference it will immediately become available for garbage collection, so it will be finalised, but that's not ideal.

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    If the performance hit of finalization is a problem you can load the image like this instead:-
    vbnet Code:
    1. '
    2.     Private Function LoadImage(ByVal path As String) As Bitmap
    3.  
    4.         Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read)
    5.         Dim originalBmp As Bitmap = Bitmap.FromStream(fs)
    6.  
    7.         Dim copyBmp As Bitmap = New Bitmap(originalBmp.Width, originalBmp.Height, originalBmp.PixelFormat)
    8.         Dim g As Graphics = Graphics.FromImage(copyBmp)
    9.  
    10.         g.DrawImage(originalBmp, 0, 0, originalBmp.Width, originalBmp.Height)
    11.         g.Dispose()
    12.         originalBmp.Dispose()
    13.         fs.Close()
    14.  
    15.         Return copyBmp
    16.  
    17.     End Function

    The idea is to return a Bitmap that is not optimized by a backing stream.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  10. #10
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,243

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Can you not just do:
    Code:
    Dim imgPath As String = <path to image>
    Dim bmp As Bitmap
    
    Using fs As New FileStream(imgPath, FileMode.Open)
        bmp = New Bitmap(fs)
    End Using
    
    '   blah
    
    bmp.Save(imgPath)

  11. #11
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    vbnet Code:
    1. '
    2. Using fs As New FileStream(imgPath, FileMode.Open)
    3.     bmp = New Bitmap(fs)
    4. End Using

    The above is the whole problem. When a Bitmap is created from a Stream object, GDI+ uses this Stream to optimize its operations. You cannot close it before disposing of the Bitmap otherwise you're going to get exceptions when trying to perform operations on them. The function in my previous post creates a Bitmap not backed by a Stream by copying the image to a new Bitmap object created without a Stream.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  12. #12
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,243

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    OK. Fair enough.

    Interestingly, nothing bad seems to happen. Even when I delete the original file, I can still manipulate the bitmap. Doesn't mean it won't fall over eventually, though.

    I guess this goes to my lack of understanding of how GDI+ operates under the hood. Looking at it from the outside, I can't imagine how a bitmap object created from a stream would be any different to a bitmap created by the overload that takes dimensions.

    However, I do notice that the documents state:
    You must keep the stream open for the lifetime of the Bitmap.
    so I shall shut up

  13. #13
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,636

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Quote Originally Posted by Inferrd View Post
    Interestingly, nothing bad seems to happen. Even when I delete the original file, I can still manipulate the bitmap. Doesn't mean it won't fall over eventually, though.
    Its not very predictable but keep manipulating it in various ways and it would eventually bomb out with something like a "Generic GDI+ error"...Oh and you don;t have to delete the file to test it, you just have to close the stream.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  14. #14
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,070

    Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Quote Originally Posted by glasner1982 View Post
    Errors I've got:

    (1) A generic error occured in GDI+

    (2) Value of type 'System.Drawing.Image' cannot be converted to 'WindowsApplication1.Image'

    (3) ArgumentException was unhandled
    parameter is not valid

    What am I doing wrong? Is there something I'm missing? Another way I should do this? I've also tried using a button, panel, and a retangle shape instead of a picturebox with no luck. I tried using the backgroundimage property instead of the image prop with no luck. I read somewhere not to use the .load but instead use .fromfile..... again no luck. so I am completely stummped. I've thought about trying to convert the image to bmp since it seems easier to save a bmp, but i really would like the image to be saved as a jpeg. Im using visual basic 2010 express and if anyone could please help me out, I would be most greatful. Thank you and someone please please please help me!!

    sorry this was so long. I just wanted to make sure im totally clear on what im trying to accomplish and what i've done so i hopefully get the help i need. Thanks all!!
    (1). Assuming this is caused by trying to overwrite the original image, use the PictureBox.Load or LoadAsync method instead of setting the Image property. Ignore what you read. These methods do not lock the input file, so you can overwrite it when necessary.

    (2). Put square brackets round your variable name [image], or use a different identifier. You are confusing the poor compiler.

    (3). Maybe (3) will go away if you fix (2).

    BB

  15. #15

    Thread Starter
    New Member
    Join Date
    May 2012
    Posts
    14

    Resolved Re: How Can I save a picture as a JPEG file? I NEED HELP!!

    Thanks everyone for your help!! I took information from each of you and found my own solution. And I did it with only 4 lines of code!!

    Here's how I did it. Make a form with a picturebox, a button, a SaveFileDialog and an OpenFileDialog. Do not change any properties of either dialog. Double click on all 4 components.
    Here's the code:

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            SaveFileDialog1.ShowDialog()
        End Sub
    
        Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
            OpenFileDialog1.ShowDialog()
        End Sub
    
        Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
            PictureBox1.ImageLocation = OpenFileDialog1.FileName
        End Sub
    
        Private Sub SaveFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SaveFileDialog1.FileOk
            PictureBox1.Image.Save(SaveFileDialog1.FileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
        End Sub
    
    End Class
    I hope this helps anyone that has been having this problem. This was done with Visual Basic 2010. Should work with 2008 as well. Thanks again everyone!

    Brian (not so noobish anymore)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width