Good day,

1. Do anybody has already done code for image processing application in VB.net? in a case of none, how can I process image for (saturation, intensity, brightness, hue, darkness e.t.c)

2. What code can I pass for a button so that when I click it, PictureBox will show the next image and on until there is no image in the specified folder.

Thank you guys for your assistance.

Recommended Answers

All 10 Replies

' BASIC IDEA FOR CYCLING THRU PICTURES IN A DIRECTORY -Cj Welborn
' You might want to check the file extension to make
' sure its a valid file. like:
' If LCase(Strings.Right(sPictureFiles(iCurrentPicture),3)) <> "jpg" Then 
'   Msgbox("Wrong Format!")
' End If
'  ....or use Select Case LCase(Strings.Right............
'  you would have to check all the valid extensions, not just JPG..
Public Class Form1
    Dim sPictureDirectory As String = My.Computer.FileSystem.SpecialDirectories.MyPictures & "\art\"
    Dim sPictureFiles() As String 'List of pictures in a directory
    Dim iCurrentPicture As Integer = -1 'Current Picture Index (None at first)

    Sub GetPictureFiles()
        'Get a list of all files in a directory
        sPicturefiles = IO.Directory.GetFiles(sPictureDirectory)
        'No files?
        If sPicturefiles.Count = 0 Then
            MessageBox.Show("No Pictures!")
            Exit Sub
        End If
    End Sub

    Sub ShowNextPicture()
        'No pictures?
        If sPictureFiles.Count = 0 Then Exit Sub
        'Get Next Picture
        iCurrentPicture += 1
        'Last picture? Go back to beginning... ( 0 )
        If iCurrentPicture > (sPictureFiles.Count - 1) Then iCurrentPicture = 0

        Try
            'Convert to Image Object
            Dim imgNext As Image = Image.FromFile(sPictureFiles(iCurrentPicture))
            'Display Image
            PictureBox1.Image = imgNext
        Catch ex As Exception
            MessageBox.Show("Could not load file:" & vbNewLine & sPictureFiles(iCurrentPicture))
        End Try

    End Sub
    'FORM_LOAD (Get picture files...)
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        GetPictureFiles()
    End Sub
    'BTN_CLICK (Show next picture...)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ShowNextPicture()
    End Sub

End Class

Hi, Chriswelborn

I appreciate your kindness but it has not answer my questions yet;

Pls be precise on how the code works.

Thank You.

Oh, sorry. I always assume that people already know some of this stuff. A detailed explanation is on the way, later on today. As far as processing the image, the hue, saturation, contrast, etc. There are ActiveX controls available to do this. I would google it.

Member Avatar for Unhnd_Exception

Heres Brightness and Darkness. You can do hue and saturation as well if you learn how to use the color matrix and image attributes classes.

Tried to comment it. Hopefully it makes enough sense so you can get pointed in the right direction.

Imports System.Drawing.Imaging

Public Class Form3
    Private Alpha As Single = 1
    Private Red As Single = 1
    Private Green As Single = 1
    Private Blue As Single = 1
    Private ImageProcessing As Bitmap

    Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        TrackBar1.Minimum = 0
        TrackBar1.Maximum = 80
        TrackBar1.Value = 40

        'This will resize the bitmap to fit in the picturebox
        'and keep the same aspect ratio of the image.
        ImageProcessing = ResizeBitmap(My.Resources.Brad, PictureBox1.ClientSize)

        'I threw the ResizeBitmap function in here because its useful and
        'the Brad image is large so i wanted it shrunken down so it would
        'fit on the screen.
    End Sub

    Private Sub TrackBar1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.ValueChanged
        'The track bar starts out in the middle. 40
        'Anything over the middle increase the rgb
        'that will make it brighter
        'Anything under the middle decrease the rgb
        'that will make it darker

        Dim value As Single = TrackBar1.Value / ((TrackBar1.Maximum - TrackBar1.Minimum) / 2)
        'when the track bar in the middle
        '40 / (80 - 0) / 2 = 1

        'when the track bar at 25%
        '20 / ((80 - 0) / 2) = .5

        'The rgb will be set at .5 in this case.  When the paint function
        'is called it will display the colors at 50% of there value
        ' causing then to go towards 0 which rgb of 0,0,0 = black.

        Red = value
        Blue = value
        Green = value

        PictureBox1.Refresh()

    End Sub

    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
        'You will need to learn about the ColorMatrix.
        'You should be able to due hue and saturation
        'with it as well.
        Dim ColorVector As Single()() = {New Single() {Red, 0, 0, 0, 0}, _
                                         New Single() {0, Green, 0, 0, 0}, _
                                         New Single() {0, 0, Blue, 0, 0}, _
                                         New Single() {0, 0, 0, Alpha, 0}, _
                                         New Single() {0, 0, 0, 0, 1}}

        Dim ColorMatrix As New ColorMatrix(ColorVector)
        Dim ImageAttributes As New ImageAttributes

        ImageAttributes.SetColorMatrix(ColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap)

        e.Graphics.DrawImage(ImageProcessing, New Rectangle(0, 0, ImageProcessing.Width, ImageProcessing.Height), 0, 0, ImageProcessing.Width, ImageProcessing.Height, GraphicsUnit.Pixel, ImageAttributes)

        ImageAttributes.Dispose()
    End Sub

    Private Function ResizeBitmap(ByVal bmp As Bitmap, ByVal maxSize As Size) As Bitmap
        If bmp Is Nothing Then Return Nothing

        Dim NewSize As Size = bmp.Size
        Dim scale As Double = 1

        If bmp.Width > maxSize.Width Then
            'Image wider than max width. Scale it down.
            scale = maxSize.Width / bmp.Width
            NewSize.Width = CInt(NewSize.Width * scale)
            NewSize.Height = CInt(NewSize.Height * scale)
        End If

        If (bmp.Height * scale) > maxSize.Height Then
            'Image height is taller than the max height 
            'even after scaling its width. Scale it again.
            scale = maxSize.Height / (bmp.Height * scale)
            NewSize.Width = CInt(NewSize.Width * scale)
            NewSize.Height = CInt(NewSize.Height * scale)
        End If

        Dim ResizedImage As New Bitmap(NewSize.Width, NewSize.Height)
        Dim G As Graphics = Graphics.FromImage(ResizedImage)
        G.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        G.DrawImage(bmp, 0, 0, NewSize.Width, NewSize.Height)
        G.Dispose()
        Return ResizedImage

    End Function

End Class
commented: Informative and well formed code :) +1

Ok, I commented this code to DEATH, and made my Variable Names very long and descriptive. (It's better to keep them short and save typing I think) I'm pretty sure i've made it sound more complicated than it really is, I'm not one to write tutorials. Anyway, if you collapse all the comments the code will be easier to read, and you can read the comments only when you need to. I hope this helps you, I'm afraid I can't explain it any better than this. The main thing is Navigating String Arrays, IO.Directory Object, and Image Object. If you want to know more maybe you could look up those terms using google or something.
1) Get all file names in my Directory
2) Store them in a String Array
3) Update the position in that String Array when the user clicks Button1
4) Store the current position
5) Load image from filename found in String Array at current position
6) Assign our loaded image to PictureBox1.Image property

Public Class Form1
    'This is what directory you want to look for pictures in.. 
    '  ...I set it to the \My Pictures\ directory because most people store pictures there
    '  ...you can set sPictureDirectory to where ever you store your pictures...
    Dim sPictureDirectory As String = My.Computer.FileSystem.SpecialDirectories.MyPictures 
    'This is a String Array containing all files in the My Picture directory (sPictureDirectory)
    '  ...it will be used for initial storing of filenames,and  cycling thru pictures.
    '  It Holds:   sPictureFiles(0) = "c:\myfirstpicture_inthisdirectory.jpg"
    '              sPictureFiles(1) = "c:\theNextpicInThisDirectory.bmp"
    '              sPictureFiles(2) = ... and so on until there are no more files in that directory
    Dim sPictureFiles() As String
    'This is the current index, or position in the sPictureFiles Array
    ' ...I set it to -1 because no picture is chosen, when the user clicks Button1 for
    ' ...the first time, ShowNextPicture will set it to 0 (the first picture in sPictureFiles)
    ' ...and from then on it will add +1 and show THAT picture
     Dim iCurrentPicture As Integer = -1 'Current Picture Index (None at first)

    'Sub to Get Pictures, a.k.a load all filenames located in sPictureDirectory into sPictureFiles Array
    Sub GetPictureFiles()
        'Get a list of all files in a directory (sPictureDirectory = \My Pictures\)
        '  ...this does not only list picture files, it lists ALL files, so 
        '  ...hopefully you will have ONLY picture files in the directory, or you
        '  ...will have to check the file extension before you try to load it. (Explained later on)
        sPictureFiles = IO.Directory.GetFiles(sPictureDirectory)
        'Check to see if any files were loaded into sPictureFiles array, incase no files are in the
        ' ...directory, or if some uncommon error occurred.
        If sPictureFiles.Count = 0 Then
            'If no picture files were loaded, then Count (number of items in sPictureFiles Array)
            '  ...will be 0. Without NO pictures, we will get an error when we try to load them
            '  ...later on.
            MessageBox.Show("No Pictures!")
            'I just put a simple little MessageBox to let you know there are no files.
            '  ...You could really do anything you want here. Like shutdown the program, Exit Sub,
            '  ...MessageBox.Show("Please choose another directory!"), or something..
        End If
    End Sub

    'Sub to show the next picture, used when Button1 is clicked, or where ever else you would want.
    Sub ShowNextPicture()
        'Check to see if we have picture filenames loaded into the sPictureFiles Array.
        '  ...If we have no filenames loaded into the array, we have no pictures, 
        '  ...and we will get an error. It's best to Exit Sub if this happens.
        If sPictureFiles.Count = 0 Then Exit Sub

        'Get Next Picture, We start at -1 in the sPictureFiles Array (No Item). We add +1 to the
        '  ...current index to go to the next filename in the array. Since we started at -1, the very 
        '  ...first time the user clicks Button1 then -1 + 1 = 0 (0 is the starting point of every String Array).
        '  ...Since we declared iCurrentPicture Globally the program will always keep track of where
        '  ...its at, no matter where we use it or modify it.
        iCurrentPicture += 1
        'Is this the last filename in the array? What is the last filenames index? It is 
        '  ...(sPictureFiles.Count - 1) because if there are 7 items in the array, starting at 0
        '  ...counting up we get 6. (0,1,2,3,4,5,6). sPictureFiles.Count IS 7, so the last
        '  ...index is 6 (7-1 = 6) -or- (sPictureFiles.Count - 1 = 6)
        '  ...IF STATEMENT:
        '  ...If we added +1 to iCurrentPicture and it is now greater than the last index,
        '  ...we need to go back to the beginning (0).
        '  ... So if current index > last index then current index = 0
        If iCurrentPicture > (sPictureFiles.Count - 1) Then iCurrentPicture = 0

        'Check File Extension, make sure we are trying to load the correct Image Format into the PictureBox1.
        'Make a string containing all acceptable image file formats for PictureBox1
        Dim sAcceptableFileExtensions As String = "jpg gif jpeg bmp wmf png"
        'If "jpg gif jpeg bmp wmf png" does not contain our current file extension then skip this file.
        '  ...InStr(StringToLookIn, StringToLookFor) returns the first character of StringToLookFor's
        '  ...position in StringToLookIn if StringToLookFor is found. Otherwise it returns 0 if it is not found.
        '  ...We are looking in sAcceptableFileExtensions for LowerCase last 3 characters in sPictureFiles(iCurrentPicture)
        '  ...In other words if sPictureFiles(iCurrentPicture) = "c:\MyBadPicture.PsD" then
        '  ... LCase(Strings.Right(sPictureFiles(iCurrentPicture), 3)) returns "psd"
        If InStr(sAcceptableFileExtensions, LCase(Strings.Right(sPictureFiles(iCurrentPicture), 3))) = 0 Then
            'Exit Sub, DO NOT LOAD IMAGE , If it had a bad file extension. (Not in our sAcceptableFileExtensions)
            Exit Sub

            'Program will not go any further, we will not try to load the image if it had the wrong
            '  ...file extension.

            'It would probably be better to find bad file extensions and remove them from the
            '  ...sPictureFiles Array in GetPictureFiles, before ShowNextPicture ever happens
            '  ...but I think I have already commented this thing to death and I do not want to go there
            '  ...right now. Sorry.
        End If

        'TRY STATEMENT:
        '  Loading an incorrect format, or a file that is already being used somewhere else, 
        '  ...among many other things, will cause an error. So we need to catch any errors in a
        '  ...TRY Statement. In other words, TRY this and CATCH any ERRORS. A.k.a.
        '  ...TRY loading image from file, CATCH loading image error, on ERROR: msgbox("could not load")
        Try
            'Convert to Image Object (Using filename to load the image)
            '  ...Image Object is what PictureBox1.Image is expecting, we can't just say
            '  ...PictureBox1.Image = "C:\myfile.jpg" !!!!! THIS WILL NOT WORK
            '  ...We need to use Image.FromFile(filename) to create an Image from a FileName
            '  ...The filename we are using is sPictureFiles(iCurrentPicture), whatever iCurrentPicture
            '  ...is at the time. imgNext is now an Image object From our File that we can do alot of 
            '  ...things with, right now we just want to assign it to PictureBox1's Image property.
            Dim imgNext As Image = Image.FromFile(sPictureFiles(iCurrentPicture))
            'Display Image , or assign our new Image we made (imgNext) to PictureBox1's Image Property
            PictureBox1.Image = imgNext
        Catch eX As Exception
            'eX is an Exception Object (Error Object), We won't need it if everything goes smoothly.
            'Show a MsgBox if an error occurred while either creating Image.FromFile, or 
            '  ...assigning Image to PictureBox1's Image property.
            MessageBox.Show("Could not load file:" & vbNewLine & sPictureFiles(iCurrentPicture))
            'A better way to do this would be:
            '  MessageBox.Show(eX.Message, "Load Image Error:", MessageBoxButtons.OK, MessageBoxIcon.Error)
            '  ...this would show you the ACTUAL error that occurred when loading the image.
        End Try

    End Sub
    'FORM_LOAD (Get picture files when form loads)
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Call TGetPictureFiles as soon as the form loads, to get a current list of pictures
        '  ...you may also call this somewhere else, like a "Update Pictures" button or something.
        '  ...lengthy explanations are also found in GetPictureFiles Sub..
        GetPictureFiles()

        'Write all the filenames we retrieved to the debug window.
        '  ...This is just to show you how the String Array works and what its storing
        '  ...It is NOT a NECCESSARY step, and can be deleted.
        'For 0 to sPictureFiles.Count-1 , do this:
        For i As Integer = 0 To sPictureFiles.Count - 1
            'Write all of our filenames to the debug window [current filename being sPictureFiles(i)...]
            Debug.WriteLine("Got Picture Filename (" & i.ToString & "): " & sPictureFiles(i))
        Next
    End Sub
    'BTN_CLICK (Show next picture when user clicks Button1)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Call ShowNextPicture when user clicks the button, 
        '  ...all code for shuffling through the pictures is in the ShowNextPicture Sub.
        '  ...lengthy explanations are also found in ShowNextPicture Sub..
        ShowNextPicture()
    End Sub

End Class
commented: Great coding and excellent commenting. +9
Member Avatar for Unhnd_Exception

and made my Variable Names very long and descriptive. (It's better to keep them short and save typing I think)

I like my variable names long and descriptive. When I look back on something a few months later its worth it. It can be argued. I obfuscate everything so my 50 character variable name turns into a c,b,or z on the final product anyways so any arguing should stop there.

Nice comment job by the way.

Oh man, I forgot to say something about the Debug.Writeline bit. If you have like 1,000 pictures, you might not want to Debug.Writeline(Filename) . Just delete that bit. I forget sometimes and write my For Loops or Do Loops to the debug window, just to see whats going on, only sometimes my For Loops get very long and Visual Studio gets stuck trying to write these 1,000 items. It won't stop until it's finished and that could take a while. It's very annoying and I'm stupid for doing it sometimes.. I just wanted to show you what IO.Directory.GetFiles() stored in sPictureFiles() Array.

Unhnd_Exception, thank you. And I do like my Variable Names descriptive, just a little shorter than that. Like sPicFiles instead of sPictureFiles, or sFileExts instead of sAcceptableFileExtensions. So I agree with you, and the obfuscator is a good idea too. I meant to tell you nice job with the Image Processing. I thought it was possible with the framework but I never really got into it. I'm gonna take your snippet and play around with it, see if I can get the Hue thing going. Not that I need it, It's just an ongoing learning process kindof thing. I think any programmer can relate to that. At least I hope so.

Member Avatar for Unhnd_Exception

I don't need it either. I posted it somewhere else here. One thing you can do with that is change the R,G,B seperately. My code changes them all at the same time. You will get different effects by adding other track bars only changing one of the values.

One cool thing you can do with it is change the transparency of the image by manipulating the A value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.