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
 
 
 
 
 
 
TitleAdd a watermark to an image
DescriptionThis example shows how to add a watermark to an image in Visual Basic 6. It loops over the pixels in the background image and the watermark image, combining them so parts of the watermark are transparent and others are translucent.
Keywordswatermark, image, image processing
CategoriesGraphics
 
Subroutine DrawWatermark combines the images. It saves the color of the watermark pixel in the upper left corner and uses that as the transparent color.

Next it loops over the pixels in the watermark image. For each pixel that is not the transparent color, the program calls subroutine CombineColors to combine the watermark and background pixel colors. It sets the background image's pixel to the result.

Function CombineColors returns a linear combination of two colors.

 
' Copy the watermark image over the result image.
Private Sub DrawWatermark(ByVal wm_pic As PictureBox, ByVal _
    bg_pic As PictureBox, ByVal x As Integer, ByVal y As _
    Integer)
Const ALPHA As Byte = 128
Dim transparent As OLE_COLOR
Dim wm_clr As OLE_COLOR
Dim bg_clr As OLE_COLOR
Dim new_clr As OLE_COLOR
Dim px As Integer
Dim py As Integer

    ' Get the transparent color.
    transparent = wm_pic.Point(0, 0)

    ' Combine the images.
    wm_pic.ScaleMode = vbPixels
    bg_pic.ScaleMode = vbPixels
    For py = 0 To wm_pic.ScaleHeight - 1
        For px = 0 To wm_pic.ScaleWidth - 1
            wm_clr = wm_pic.Point(px, py)
            If wm_clr <> transparent Then
                bg_clr = bg_pic.Point(x + px, y + py)
                new_clr = CombineColors(wm_clr, bg_clr, _
                    ALPHA)
                bg_pic.PSet (x + px, y + py), new_clr
            End If
        Next px
    Next py
End Sub

' Return (A * clr1 + (255-A) * clr2)\256.
Private Function CombineColors(ByVal clr1 As OLE_COLOR, _
    ByVal clr2 As OLE_COLOR, ByVal A As Byte) As OLE_COLOR
Dim r1 As Long
Dim g1 As Long
Dim b1 As Long
Dim r2 As Long
Dim g2 As Long
Dim b2 As Long

    b1 = Int(clr1 / 65536)
    g1 = Int((clr1 - (65536 * b1)) / 256)
    r1 = clr1 - ((b1 * 65536) + (g1 * 256))

    b2 = Int(clr2 / 65536)
    g2 = Int((clr2 - (65536 * b2)) / 256)
    r2 = clr2 - ((b2 * 65536) + (g2 * 256))

    r1 = (A * r1 + (255 - A) * r2) \ 256
    g1 = (A * g1 + (255 - A) * g2) \ 256
    b1 = (A * b1 + (255 - A) * b2) \ 256

    CombineColors = r1 + 256 * g1 + 65536 * b1
End Function
 
You could use GetDIBits and SetDIBits to manipulate the pixels more quickly but the program would be a lot more complicated. This version is fast enough for relatively small watermarks.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated