Page 1 of 1

Some small Graphics and Image Manipulation projects Rate Topic: -----

#1 ricardosms  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 73
  • View blog
  • Posts: 301
  • Joined: 02-April 10

Posted 20 March 2012 - 02:46 PM

Some small Graphics and Image Manipulation projects


I always regard myself as a beginner, I keep learning from others or figuring out things by myself by doing and experimenting, and whatever I learn I use to adjust what I already knew, and when possible, show it to others. I was an educator in the past.

Lately, I have played a lot with graphics and images, and I think this subject would allow for a tutorial "for beginners" that will show some issues that I have found and tried.

A touch of color improves everything (That's why you paint your house when you want to sell it) or "An Image tells more than a thousand words", as the ancient saying goes...

When I started programming, ages ago, the computers were almost the size of a 2 storey house, there was nothing resembling a keyboard or a mouse, and there was no monitor attached to it. Data was entered by other means.

Output? Maybe an aborted program or a printout on a green and white continuous form. Today, the screen gives information and sometimes feedback on what is going on, and it shows text and images.

Uses for the computer are almost infinite, but the visual part is the more "Eye Catching", And if you are reading this tutorial, probably you have "Visual" Studio, which allows for a rapid application development on a type of program, mostly visual, named "Windows Forms Application" instead of a console application, or other types.

An image on the computer screen is the interpretation of an array of "bytes", permanently or temporarily stored on some part of your computer. This is a string of bits, like anything else in the computer, and what are they? Just magnetic fields(floppy), voltage levels (memory) or color variations(cd) or maybe something else that can be decoded.

Like anything else, as I said, images can be manipulated in several ways. The Visual programming has tons and tons of libraries, resources, routines and methods to do so, and you only need to learn how to use then to accomplish what you have in mind. Impossible?
Maybe at the present, but when you have enough interest, you will figure most things out.

There are different standards or formats to order the information into images, so they can be understood and represented by the computers, some are no longer used, other are proprietary of the designer of certain graphics programs, for exclusive use.

Popular and available formats are: "Ico", "Bmp", "Gif", "Jpeg", "Tiff", "Png".

You can check this link:


On a windows form you can display images on different controls or on the form itself. You paint the image using a bitmap and a graphics object or you assign the property to some of them, from a file or maybe a resource that is part of your program. Some controls can also have a background image.

In this tutorial I will present you four small projects using graphics and images:

Ok!, Let's say you started a windows form program. You can draw different objects or shapes on the main form.

I Use Random Functions to draw shapes on a form, which generate a value set by the limits, "low" and "high", and the method "next", but it will not work properly if you don't make it "static" in the generating function or routine. It will repeat the same value every time you call it.

In order for it to work it has to be declared as this:

Static Random1 As New Random
Random1 = Random1.Next(Minimum, Maximum)

So, the "Next" will generate a new value every time you enter the function.

The lower limit doesn't need to be set if you are using zero. The maximum generated value will be high-1, so if you want that number too, you have to use a higher "high".

The first project is called "DrawCircles", but really what it does is to draw ellipses, rectangles, numbers and unicode characters at random positions, colors and sizes.

Attached Image

There is not too much to it. We use a "select Case" structure to keep track of what to output to the form. When the timer goes off, the static variable "Shape" tells the program what operation to perform. A static variable is a special one, it keeps it's value on successive calls to a routine, instead of resetting or creating it again every time, so if you change it (add 1 to it), when it comes back will have this value instead of the former one. I use also the "MOD" mathematical operation, so I can have four different operations to do. The timer has a short interval to make the objects appear quicky. You start and stop the sequence or clear the form by pressing the command buttons. If you change the form size, the generated position for the shapes will change too, according to the form's width. We are using 3 methods: "FillEllipse", "FillRectangle" and "DrawString". The DrawString is used on two ways, to output a
number and to output a "Wide character" (Unicode). All these methods are part of the system.Drawing, System.Drawing.Drawing2D and System.Drawing.Imaging that you import at the beginning of all graphics programs.

Here is the code:

Imports System.Drawing.Drawing2D

Public Class Form1

    'Generate a random integer number from zero to the width of the screen
    Public Function RandX() As Integer
        Dim Xr As Integer
        Static yr As New Random

        Xr = yr.Next(0, Me.Width)

        Return Xr
    End Function

    'Generate width or height of a rectangle containing the ellipse with 5 as minimum and 299 as maximum
    Public Function RandomSide() As Integer
        Dim Rad As Integer
        Static RanRadio As New Random
        Rad = RanRadio.Next(5, 300)
        Return Rad
    End Function

    'Generate 4 components for a color, Red, Green, Blue and Transparency (0 t0 255)

    Public Function rndColor() As Integer
        Dim Num As Integer
        Static Random1 As New Random 'So it will give you a new one every time
        Num = Random1.Next(0, 256)
        Return Num
    End Function

    Public Function RandomChar() As Integer
        Dim Num As Integer
        Static ran As New Random
        Num = ran.Next(32, 60000)
        Return Num
    End Function

The sequence is started by pressing "Start", that enables the timer and when the tick gets off it calls the drawing operation. Every tick draws an object. You stop by pressing the other button, so you disable the timer. If you press clear, it will erase everything.
These images are not permanent.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End Sub

    'Stop Cycle
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    End Sub

    'Use graphics object on Form to draw and fill ellipse with the random values generated
    'and repeat until stopped by stop button click

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        Static Shape As Integer = 0
        Shape += 1
        Dim Letter As String

        Dim clr As Color = Color.FromArgb(rndColor, rndColor, rndColor, rndColor)
        Dim rd As Integer = RandomSide()
        Dim MyBrush As New SolidBrush(clr)
        Dim myPen As New Pen(MyBrush)
        Dim Afont As New Font("Comic Sans MS", 60, FontStyle.Bold, GraphicsUnit.Pixel)

        Dim gfx As Graphics
        gfx = Me.CreateGraphics
        Select Case Shape Mod 4
            Case 0
                gfx.FillRectangle(MyBrush, RandX, RandX, RandomSide, RandomSide)

            Case 1
                gfx.FillEllipse(MyBrush, RandX, RandX, RandomSide, RandomSide)

            Case 2
                gfx.DrawString(RandomChar, Afont, MyBrush, RandX, RandX)

            Case 3
                'Unicode Characters
                Letter = ChrW(RandomChar())
                gfx.DrawString(Letter, Afont, MyBrush, RandX, RandX)

        End Select

    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        'Clear Form
        Dim gfx As Graphics
        gfx = Me.CreateGraphics

    End Sub
End Class

The Second Project called "DrawRays" also has a timer to measure intervals, but this one will draw lines and ellipses at calculated positions and around a central point using random colors, created with a different method, when the mouse is dragged on the form:

Attached Image

Here we generate colors at random by using the random function:

        Color = RandomNumber(&HF0000021, &HFFFFFFFE)

in VB, a long integer representing color is created from RGB values:

Color = B   *  &FF00&     +   G   * &HFF&    +   R 
'or this without Hex notation 
Color = (256 * 256 * B)/>   + G * 256 + R 

Please check here:


Ok, now we continue with our program. Here we have a picturebox and we will draw on it. What we are doing here is generating colors at random and generating location of points with mathematical equations using the mouse position and movement, then tracing color lines to these points, but although we are using a focal point, we are not doing it symmetrically, we use factors to alter the distance and we mix the "X" and "Y" values, so we get somehow a circular or elliptical motion of the lines around an edge that goes from the top left corner to the bottom right corner. Also to add to the visual effect, we create ellipses and paint them on the form. They happens on two sets and the particular colors are inverted for one of them. If you click and move the mouse around the screen you will see the ellipses
changing color and size, but around the same point. If you click and do the same on another area of the screen, you will see different locations. At the same time you will see the lines been drawn around. If you move the mouse quick enough, you will have some lines of the same color, that depends on the timer interval.

Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class Form1
    'To keep track of button clicked
    Public MouseControl As String
    Dim Color As Int32
    Dim fx, fy As Double

   'Coordinates of point where the mouse button is pressed down to establish the starting point for a line
    Public p As Integer
    Public q As Integer

    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles  
        p = e.X
        q = e.Y

       'Start measuring the time interval to generate point and color.
        Timer1.Enabled = True

        Select Case e.Button
            Case MouseButtons.Left
                MouseControl = "L"
            Case MouseButtons.Right
                MouseControl = "R"
            Case MouseButtons.Middle
                MouseControl = "M"
            Case MouseButtons.XButton1
                MouseControl = "X1"
            Case MouseButtons.XButton2
                MouseControl = "X2"
            Case MouseButtons.None
                MouseControl = Nothing
        End Select
    End Sub

The point structures are assigned to an array of points. There are two points for each line and we use "factx" and "facty" as factors to multiply "e.X" and "e.Y" so our points are away from the mouse pointer that is generating the event. We will use two graphics objects to draw on the image. One for the circles(360 degrees arcs) and other for the lines. Also we are using a graphics path. You could see it been used on other tutorials in this site:




    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles  
        fx = fx + RandomNumber(1, 20) / 1.5 + 15
        fy = fy + RandomNumber(1, 8) / 1.75 + 10
        Dim myArray As Point() = {New Point(-e.Y + 200, -e.X + 200), New Point(e.Y * 1.7, e.X * 1.5)}
        Dim cle, cir As Graphics
        Dim factx, facty As Integer
        Dim myPath As New GraphicsPath
        Dim mykolor, InvKolor As Color
        cle = PictureBox1.CreateGraphics
        cir = PictureBox1.CreateGraphics
        If MouseControl = "L" Then

            'Here the lines created from the array are added to the path for drawing.


            InvKolor = Color.FromArgb(&HFFFFFFFE - Color) 'Opposite Color
            mykolor = Color.FromArgb(Color)
            factx = e.X / 4
            facty = e.Y / 2

           'Here we draw the lines
            cle.DrawPath(New Pen(mykolor), myPath)

            'And here we draw the circles.
            If (factx > 1) And (facty > 1) Then
                cir.DrawArc(New Pen(mykolor, 10), p, q, facty, factx, 0, 360)
                cir.DrawArc(New Pen(InvKolor, 10), q, p, factx, facty, 0, 360)
            End If
        End If

Using the values set at the beginning of the program about the mouse events saved on string variables we clear the path to be ready for the next operation.

        If MouseControl = Nothing Then
        End If
    End Sub

    Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        Timer1.Enabled = False
        MouseControl = Nothing
    End Sub

This is a random generating function :

    Public Function RandomNumber(ByVal low As Int32, ByVal high As Int32) As Int32
        Static RandomNumGen As New System.Random
        Return RandomNumGen.Next(low, high + 1)
    End Function

And a couple of accessory functions; the clearing of the canvas and the color generating function called by the timer tick.

    Private Sub ClearToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  
        PictureBox1.Image = Nothing
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Color = RandomNumber(&HF0000021, &HFFFFFFFE)
    End Sub
End Class

On two of the former projects we did draw on the form itself, but there are other controls that can show images; buttons, datagridviews, numeric up downs, labels... Although they can, the best suited one to do so is the Picturebox. as you saw on the "DrawRays" project.

Our next project also uses a picturebox to draw on it.

The third Project "Magnet" has a panel set to autoscroll = true and a picturebox inside it with the sizemode set to autosize. I called it magnet because it catches and holds colors.
Here we will also draw lines from point to point, but there is a catch: the points are generated by the mouse move and kept in arrays of point structures. Moving the mouse freely over the picturebox we draw a line from each point to the next. But don't take a seat yet, we are actually doing it on five pixels at a time. What effect do we get? Let's see!

I have 2 radiobuttons, one for "Same Color", the other for "changing Color" and, depending on the selection, we will either pick five colors when the mouse goes down and use them to draw a path, or get five new colors as the mouse moves and use them for the drawing.
This is not a timed operation; it depends on how fast you move the mouse.

It will draw a multicolor streak or could be used for smudging an image if you go fast back and forth (like a zigzag movement) over certain area of the image.

Attached Image

We are picking the colors using getpixel(). The five point structures are at the mouse pointer, 4 pixels to the left, 4 pixels to the right, 4 pixels above and 4 pixels below. Here we get the colors and the positions. Please note that because we are calculating pixels around the mouse pointer, and that you could go close to the edge, some of the points will be out of the image (inexistent) and that will produce an error, so we use a try catch structure and ignore the error and go to the next point. We are using a pen that is 4 pixels thick, so it covers the spaces in between the points. Everything that is happening goes on in the two handlers "Mousedown" and "mousemove".

Here you could see how I did it:

Imports System.Drawing

Public Class Form1
    'initial colors
    Dim ClearColor1 As Color = Color.White
    Dim ClearColor2 As Color = Color.White
    Dim ClearColor3 As Color = Color.White
    Dim ClearColor4 As Color = Color.White
    Dim ClearColor5 As Color = Color.White

    'arrays of points
    Private m_Points1() As Point
    Private m_Points2() As Point
    Private m_Points3() As Point
    Private m_Points4() As Point
    Private m_Points5() As Point
    Private m_MaxPoint As Integer

    Private Sub Work_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Work.MouseDown
        'Initial points and initial colors
        Dim bmx As Bitmap
        bmx = New Bitmap(Work.Image)
        ClearColor1 = bmx.GetPixel(e.X, e.Y)
        ClearColor2 = bmx.GetPixel(e.X - 4, e.Y)
        ClearColor3 = bmx.GetPixel(e.X + 4, e.Y)
        ClearColor4 = bmx.GetPixel(e.X, e.Y - 4)
        ClearColor5 = bmx.GetPixel(e.X, e.Y + 4)
        bmx = Nothing
        m_MaxPoint = 0
        ReDim m_Points1(m_MaxPoint)
        ReDim m_Points2(m_MaxPoint)
        ReDim m_Points3(m_MaxPoint)
        ReDim m_Points4(m_MaxPoint)
        ReDim m_Points5(m_MaxPoint)
        m_Points1(m_MaxPoint).X = e.X
        m_Points1(m_MaxPoint).Y = e.Y

        m_Points2(m_MaxPoint).X = m_Points1(m_MaxPoint).X - 4
        m_Points2(m_MaxPoint).Y = m_Points1(m_MaxPoint).Y
        m_Points3(m_MaxPoint).X = m_Points1(m_MaxPoint).X + 4
        m_Points3(m_MaxPoint).Y = m_Points1(m_MaxPoint).Y
        m_Points4(m_MaxPoint).X = m_Points1(m_MaxPoint).X
        m_Points4(m_MaxPoint).Y = m_Points1(m_MaxPoint).Y - 4
        m_Points5(m_MaxPoint).X = m_Points1(m_MaxPoint).X
        m_Points5(m_MaxPoint).Y = m_Points1(m_MaxPoint).Y + 4
    End Sub

    Private Sub Work_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Work.MouseMove
        If (e.Button = MouseButtons.Left) Then
            ' Do nothing if we're not selecting a region.
            If m_Points1 Is Nothing Then Exit Sub
            Dim bmx As Bitmap
                ' Save the new points and redimension arrays.
                m_MaxPoint += 1
                ReDim Preserve m_Points1(m_MaxPoint)
                ReDim Preserve m_Points2(m_MaxPoint)
                ReDim Preserve m_Points3(m_MaxPoint)
                ReDim Preserve m_Points4(m_MaxPoint)
                ReDim Preserve m_Points5(m_MaxPoint)
                If e.X < 4 Then
                    m_Points2(m_MaxPoint).X = e.X

                    m_Points2(m_MaxPoint).X = e.X - 4
                End If
                m_Points1(m_MaxPoint).X = e.X
                m_Points1(m_MaxPoint).Y = e.Y
                m_Points2(m_MaxPoint).Y = e.Y
                If e.X > Work.Width - 4 Then
                    m_Points3(m_MaxPoint).X = e.X

                    m_Points3(m_MaxPoint).X = e.X + 4

                End If
                m_Points3(m_MaxPoint).Y = e.Y
                m_Points4(m_MaxPoint).X = e.X
                If e.Y < 4 Then
                    m_Points4(m_MaxPoint).Y = e.Y

                    m_Points4(m_MaxPoint).Y = e.Y - 4

                End If
                m_Points5(m_MaxPoint).X = e.X
                If e.Y > Work.Height - 4 Then
                    m_Points5(m_MaxPoint).Y = e.Y

                    m_Points5(m_MaxPoint).Y = e.Y + 4

                End If
                'create a pen object to draw the lines
                Dim MyPen1 As New Pen(ClearColor1, 4) 'Picked color
                Dim MyPen2 As New Pen(ClearColor2, 4) 'Picked color
                Dim MyPen3 As New Pen(ClearColor3, 4) 'Picked color
                Dim MyPen4 As New Pen(ClearColor4, 4) 'Picked color
                Dim MyPen5 As New Pen(ClearColor5, 4) 'Picked color

                ' Draw the latest line.
                Dim gr As Graphics = Work.CreateGraphics
                gr.DrawLine(MyPen1, _
                    m_Points1(m_MaxPoint).X, _
                    m_Points1(m_MaxPoint).Y, _
                    m_Points1(m_MaxPoint - 1).X, _
                    m_Points1(m_MaxPoint - 1).Y)
                gr.DrawLine(MyPen2, _
                    m_Points2(m_MaxPoint).X, _
                    m_Points2(m_MaxPoint).Y, _
                    m_Points2(m_MaxPoint - 1).X, _
                    m_Points2(m_MaxPoint - 1).Y)
                gr.DrawLine(MyPen3, _
                    m_Points3(m_MaxPoint).X, _
                    m_Points3(m_MaxPoint).Y, _
                    m_Points3(m_MaxPoint - 1).X, _
                    m_Points3(m_MaxPoint - 1).Y)
                gr.DrawLine(MyPen4, _
                    m_Points4(m_MaxPoint).X, _
                    m_Points4(m_MaxPoint).Y, _
                    m_Points4(m_MaxPoint - 1).X, _
                    m_Points4(m_MaxPoint - 1).Y)
                gr.DrawLine(MyPen5, _
                    m_Points5(m_MaxPoint).X, _
                    m_Points5(m_MaxPoint).Y, _
                    m_Points5(m_MaxPoint - 1).X, _
                    m_Points5(m_MaxPoint - 1).Y)

                If RadioButton2.Checked = True Then
                    bmx = New Bitmap(Work.Image)

                    ClearColor1 = bmx.GetPixel(e.X, e.Y)
                    'Not to come too close to the edge
                    If e.X < 4 Then
                        ClearColor2 = bmx.GetPixel(e.X, e.Y)
                        ClearColor2 = bmx.GetPixel(e.X - 4, e.Y)
                    End If
                    If e.X > Work.Width - 4 Then
                        ClearColor3 = bmx.GetPixel(e.X, e.Y)
                        ClearColor3 = bmx.GetPixel(e.X + 4, e.Y)
                    End If
                    If e.Y < 4 Then
                        ClearColor4 = bmx.GetPixel(e.X, e.Y)
                        ClearColor4 = bmx.GetPixel(e.X, e.Y - 4)
                    End If
                    If e.Y > Work.Height - 4 Then
                        ClearColor5 = bmx.GetPixel(e.X, e.Y)
                    End If
                    ClearColor5 = bmx.GetPixel(e.X, e.Y + 4)

                    bmx = Nothing
                End If
                ' If we go outside the edge of the image we are manipulating pixels that don't exist , so ignore
            End Try
        End If

    End Sub

End Class

What other things can be done on an image? Still lots, flip, rotate, brighten, resize, watermark, crop, blur, edge detection, cropping, translating, changing format, clipping, graphics path... and the list goes on.

Flipping vertically, horizontally or rotating by 90, 180 and 270 degrees is easy. Check this link:


Brightening, darkening, getting greyscale or sepia can be done on individual pixels, averaging values and changing them individually, but it is more efficient if you use a "ColorMatrix". It is a mathematical method done on an special array called matrix. But everything is already done for us. We only need to learn how to use this tool on the proper place, a graphics object.

The next program "Brighten" will show you how to use the colormatrix to alter an image. The buttons will convert the image to sepia or greyscale and the scrollbars will change the color balance for RED, GREEN, and BLUE components and the brightness of the image.

The colormatrix is an array of 5x5 elements and when applied will affect the image. The main diagonal from element 0,0 to element 5,5 determines the value of the main components individually. The other elements will multiply or add to these values according to the other components values. This is an extensive subject that may require to be examinated separately. Please see this link:


In the mean time, here is my small sample program:

Attached Image

This program doesn't do too much. Just takes an image and changes it's attributes. This is done using a colormatrix and an object called imageAttributes as you will see.

Imports System.Drawing.Imaging

Public Class Form1

'Changing the value of any scrollbar calls the same routine. 
'Here we don't need to use the sender object because we are only calling  another routine "setRGBBrightNess()".

    Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles  
HScrollBar1.Scroll, HScrollBar2.Scroll, HScrollBar3.Scroll, HScrollBar4.Scroll
    End Sub

The routine "setRGBBrightNess()" uses 3 variables for setting the brightness of the three RGB components on the main diagonal of our colormatrix. These are adjusted from the scrollbars on the form. They have initial values that won't change the attributes, but because the values for the intensities for the colors go from 0 to 255, and the colormatrix uses values around to 1.0F (float/single) we need a conversion, so we divide the value by 100. The adjusted brightness variable help to avoid the problem of overflowing, where we get funny colors if we go past certain range on the adjustments.

    Private Sub setRGBBrightNess()
        Dim brightness As Single = CSng(HScrollBar4.Value / 100) ' no change in brightness
        Dim contrast As Single = 1.0F ' no change in contrast

        Dim adjustedBrightness As Single = brightness - 1.0F
        Dim brtR As Single = CSng(HScrollBar1.Value / 100)
        Dim brtG As Single = CSng(HScrollBar2.Value / 100)
        Dim brtB As Single = CSng(HScrollBar3.Value / 100)
        Dim image_attr As New ImageAttributes
        Dim cm2 As ColorMatrix = New ColorMatrix(New Single()() _
            { _
            New Single() {brtR, 0.0, 0.0, 0.0, 0.0}, _
            New Single() {0.0, brtG, 0.0, 0.0, 0.0}, _
            New Single() {0.0, 0.0, brtB, 0.0, 0.0}, _
            New Single() {0.0, 0.0, 0.0, 1.0, 0.0}, _
            New Single() {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0.0, 1.0}})

'Show the values of the elements

        Label1.Text = HScrollBar1.Value.ToString
        Label2.Text = HScrollBar2.Value.ToString
        Label3.Text = HScrollBar3.Value.ToString
        Label4.Text = HScrollBar4.Value.ToString

We need to create a graphics object and a rectangle comprising the image on the picturebox. So, we transform the image and display it again on the picturebox. I have an initial image, but you can load your own image from the menu using the openfile dialog.

        Dim rect As Rectangle = Rectangle.Round(PictureBox1.Image.GetBounds(GraphicsUnit.Pixel))
        Dim wid As Integer = PictureBox1.Image.Width
        Dim hgt As Integer = PictureBox1.Image.Height

        Dim img As New Bitmap(wid, hgt)
        Dim gr As Graphics = Graphics.FromImage(img)

        gr.DrawImage(PictureBox1.Image, rect, 0, 0, wid, hgt, GraphicsUnit.Pixel, image_attr)

        PictureBox2.Image = img

    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  
        Dim f As New OpenFileDialog

            With f
                .Filter = "Image Files|*.bmp;*.gif;*.jpg;*.png;*.tif"

                If .ShowDialog = DialogResult.OK Then
                    PictureBox1.Image = Image.FromFile(.FileName)
                    'stick a distinct image object into the tag as a backup
                    PictureBox1.Tag = Image.FromFile(.FileName)
                End If

            End With

        Catch ex As Exception

            If Not f Is Nothing Then
                f = Nothing
            End If

        End Try

    End Sub

The rest of the code makes other kind of transformations, also using the colormatrix. Greyscale and sepia tone are much simpler and faster than using getpixel and setpixel functions.

    Private Sub btnSepia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSepia.Click
        PictureBox2.Image = GetSepia(PictureBox1.Image)
    End Sub
   Private Sub btnGrey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrey.Click
        PictureBox2.Image = Getgrey(PictureBox1.Image)
    End Sub

    Public Function Getgrey(ByVal im As Image) As Image
        Dim cm1 As ColorMatrix
        cm1 = New ColorMatrix(New Single()() _
        {New Single() {0.3, 0.3, 0.3, 0, 0}, _
         New Single() {0.59, 0.59, 0.59, 0, 0}, _
         New Single() {0.11, 0.11, 0.11, 0, 0}, _
         New Single() {0, 0, 0, 1, 0}, _
         New Single() {0, 0, 0, 0, 1}})

        Return DrawNewImage(im, cm1)

    End Function

    Public Function GetSepia(ByVal im As Image) As Image
        Dim cm1 As ColorMatrix
        cm1 = New ColorMatrix(New Single()() { _
        New Single() {0.293, 0.249, 0.172, 0, 0}, _
        New Single() {0.669, 0.586, 0.434, 0, 0}, _
        New Single() {0.19, 0.17, 0.14, 0, 0}, _
        New Single() {0, 0, 0, 1, 0}, _
        New Single() {0, 0, 0, 0, 1}})

        Return DrawNewImage(im, cm1)

    End Function

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  
    End Sub
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        PictureBox1.Tag = PictureBox1.Image
    End Sub

    Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
        PictureBox1.Image = PictureBox1.Tag
    End Sub

The following function is an accessory function that draws the image using as parameters the image and the colormatrix and returns an image.

    Private Function DrawNewImage(ByVal MyImage As Image, ByVal cm1 As ColorMatrix) As Image
        Dim bm As Bitmap
            Dim image_attr As New ImageAttributes
            Dim rect As Rectangle = Rectangle.Round(MyImage.GetBounds(GraphicsUnit.Pixel))
            Dim width As Integer = MyImage.Width
            Dim height As Integer = MyImage.Height
            Dim gr As Graphics
            bm = New Bitmap(width, height)
            gr = Graphics.FromImage(bm)
            gr.DrawImage(MyImage, rect, 0, 0, width, height, GraphicsUnit.Pixel, image_attr)
            Return bm
            image_attr = Nothing
        Catch ex As Exception
            MessageBox.Show("Error on Operation")
        End Try
        Return bm
    End Function

End Class

I think for now we have enough. You could check this site (DreamInCode) for other tutorials about angle rotating, cropping and others subjects. If you request some other subject, I will try to present it to you, but with no warranties. Deal?

Thank you for checking this tutorial, and please, look at the attached projects.


Attached File(s)

This post has been edited by ricardosms: 12 April 2012 - 07:28 PM

Is This A Good Question/Topic? 3
  • +

Page 1 of 1