Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse an ImageAttributes object to adjust an image's brightness in Visual Basic .NET
DescriptionThis example shows how to use an ImageAttributes object to adjust an image's brightness in Visual Basic .NET
Keywordscolor, color components, brightness, ColorMatrix, ImageAttributes, VB .NET
CategoriesVB.NET, Graphics
 
When transforming colors, Visual Basic .NET represents a color using a vector with 5 entries: red, green, blue, alhpa (opacity), and a scaling value that is 1. A ColorMatrix can transform an image's colors by multiplying each pixel's color vector by a 5-by-5 matrix. An identity matrix, with 1's down the diagonal, leaves all colors unchanged.

The following code uses a ColorMatrix to adjust the brightness of an image's pixels. (To see how this works, multiply the first matrix by the vector (r, g, b, a, 1) and notice that the result is (brt * r, brt * g, brt * b, a, 1) so the red, green, and blue values have been scaled by a factor of brt.)

When you change the program's scroll bar or enter a new value in the TextBox, the program uses this routine to adjust the image's brightness accordingly.

 
Private Sub picResult_Paint(ByVal sender As Object, ByVal e _
    As System.Windows.Forms.PaintEventArgs) Handles _
    picResult.Paint
    Dim brt As Single = hbarBrightness.Value / 100
    Dim image_attr As New ImageAttributes
    Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
        { _
        New Single() {brt, 0.0, 0.0, 0.0, 0.0}, _
        New Single() {0.0, brt, 0.0, 0.0, 0.0}, _
        New Single() {0.0, 0.0, brt, 0.0, 0.0}, _
        New Single() {0.0, 0.0, 0.0, 1.0, 0.0}, _
        New Single() {0.0, 0.0, 0.0, 0.0, 1.0}})
    Debug.WriteLine(brt)
    Dim rect As Rectangle = _
        Rectangle.Round(picSource.Image.GetBounds(GraphicsUnit.Pixel))
    Dim wid As Integer = picSource.Image.Width
    Dim hgt As Integer = picSource.Image.Height

    image_attr.SetColorMatrix(cm)
    e.Graphics.DrawImage(picSource.Image, rect, 0, 0, wid, _
        hgt, GraphicsUnit.Pixel, image_attr)
End Sub
 
This method is extremely fast so you can easily adjust brightness in real time.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated