CodeItBetter Programming Another VB Programming Blog

How to Brighten or darken a picture

Posted on November 18, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'Forms - How to Brighten or darken a picture
'Use GetDIBits to load the picture's pixel values. Adjust the color components
'so they are closeer to 0 (darker) or 255 (brighter). Then use SetDIBits to save
'the result.

Private Sub SetBrightness(ByVal pic1 As PictureBox, ByVal brightness As Single)
    Dim bitmap_info As BITMAPINFO
    Dim pixels() As Byte
    Dim bytes_per_scanLine As Integer
    Dim pad_per_scanLine As Integer
    Dim X As Integer
    Dim Y As Integer
    Dim fraction As Single
 
    ' Get the original picture's bits.
    ' Prepare the bitmap description.
    With bitmap_info.bmiHeader
        .biSize = 40
        .biWidth = Picture1.ScaleWidth
        ' Use negative height to scan top-down.
        .biHeight = -Picture1.ScaleHeight
        .biPlanes = 1
        .biBitCount = 32
        .biCompression = BI_RGB
        bytes_per_scanLine = ((((.biWidth * .biBitCount) + 31) \ 32) * 4)
        pad_per_scanLine = bytes_per_scanLine - (((.biWidth * .biBitCount) + 7) \ 8)
        .biSizeImage = bytes_per_scanLine * Abs(.biHeight)
    End With
 
    ' Load the bitmap's data.
    ReDim pixels(1 To 4, 1 To Picture1.ScaleWidth, 1 To Picture1.ScaleHeight)
    GetDIBits Picture1.hDC, Picture1.Image, 0, Picture1.ScaleHeight, pixels(1, 1, 1), _
        bitmap_info, DIB_RGB_COLORS
 
    ' Modify the pixels.
    If brightness < 0 Then
        ' Darken.
        fraction = (100 + brightness) / 100
        For Y = 1 To pic1.ScaleHeight
            For X = 1 To pic1.ScaleWidth
                pixels(pixR, X, Y) = fraction * pixels(pixR, X, Y)
                pixels(pixG, X, Y) = fraction * pixels(pixG, X, Y)
                pixels(pixB, X, Y) = fraction * pixels(pixB, X, Y)
            Next X
        Next Y
    Else
        ' Brighten.
        fraction = brightness / 100
        For Y = 1 To pic1.ScaleHeight
            For X = 1 To pic1.ScaleWidth
                pixels(pixR, X, Y) = pixels(pixR, X, Y) + fraction * (255 - pixels(pixR, X, Y))
                pixels(pixG, X, Y) = pixels(pixG, X, Y) + fraction * (255 - pixels(pixG, X, Y))
                pixels(pixB, X, Y) = pixels(pixB, X, Y) + fraction * (255 - pixels(pixB, X, Y))
            Next X
        Next Y
    End If
 
    ' Display the result.
    SetDIBits Picture2.hDC, Picture2.Image, 0, Picture1.ScaleHeight, pixels(1, 1, 1), _
        bitmap_info, DIB_RGB_COLORS
    Picture2.Picture = Picture2.Image
End Sub
Filed under: Forms Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.