Friday, October 28, 2011

Loading and Saving an Image in VB .NET

First we shall consider a form that contains two buttons: one button for opening an image(BUTOpen) and one button for saving an image (BUTSave) and a PictureBox control for showing the opened image. The form should look like this:
This form should also have an OnLoad event to initialize a bitmap object (which should hold your image):
Public Class ImgForm

    Private myBitmap As Bitmap

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        myBitmap = New Bitmap(PictureBox1.Height, PictureBox1.Width)
    End Sub

End Class
1.Loading an image

To load an image you will need to specify its filename. In most of the cases (especially when you need your user to specify which image to load), it's recommended to use the .NET OpenFileDialog class. This dialog allows the user to browse his computer in search for the image he wants to load. Also, you can specify filters, so the dialog will not show irrelevant files. All this can be put in a click event for the button BUTOpen.
   Private Sub BUTOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BUTOpen.Click
        Dim open As New OpenFileDialog
        open.Filter = "JPG files (*.jpg)|*.jpg|Bitmaps (*.bmp)|*.bmp|Gif(*.gif)|*.gif"
        If (open.ShowDialog = DialogResult.OK) Then
            myBitmap = System.Drawing.Image.FromFile(open.FileName)
            PictureBox1.Image = myBitmap
        End If
    End Sub
2.Saving an image

After you've ended modifying your image (see Drawing Lines, Shapes and Text in VB.NET), you may want to save it on your hard-disk. To do that you just need to specify the path where your image should be saved. Like I said before, if you want the user to select the location it's recommended to use a dialog. In this case, your best choice would be the inbuilt SaveFileDialog class (which is, in fact, very similar to the OpenFileDialog.). All this can be put in a click event for the button BUTSave.
    Private Sub BUTSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BUTSave.Click
        Dim save As New SaveFileDialog
        save.Filter = "JPG files (*.jpg)|*.jpg|Bitmaps (*.bmp)|*.bmp|Gif(*.gif)|*.gif"
        If (save.ShowDialog = DialogResult.OK) Then
            myBitmap.Save(save.FileName)
        End If
    End Sub

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger