Search code examples
vb.netgdi

"Tint" property when drawing Image with VB.NET


Given a color, how can I "tint" an image when I am drawing it into a picturebox with VB.NET?


Solution

  • You can use the ColorMatrix class to accomplish this:

        'Imports System.Drawing.Imaging
        ''' <summary>
        ''' Tints a bitmap using the specified color and intensity.
        ''' </summary>
        ''' <param name="b">Bitmap to be tinted</param>
        ''' <param name="color">Color to use for tint</param>
        ''' <param name="intensity">Intensity of the tint.  Good ranges are .25 to .75, depending on your preference.  Most images will white out around 2.0. 0 will not tint the image at all</param>
        ''' <returns>A bitmap with the requested Tint</returns>
        ''' <remarks></remarks>
    Private function TintBitmap(b As Bitmap, color As Color, intensity As Single ) As Bitmap         
            Dim b2 As New Bitmap(b.Width,b.Height)
    
            Dim ia As New ImageAttributes
    
            Dim m As ColorMatrix 
            m = New ColorMatrix(New Single()() _
                {New Single() {1, 0, 0, 0, 0}, _
                 New Single() {0, 1, 0, 0, 0}, _
                 New Single() {0, 0, 1, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {color.R/255*intensity, color.G/255*intensity, color.B/255*intensity, 0, 1}})
    
            ia.SetColorMatrix(m)
            Dim g As Graphics = Graphics.FromImage(b2)
            g.DrawImage(b,new Rectangle(0, 0, b.Width, b.Height), 0, 0, b.Width, b.Height, GraphicsUnit.Pixel, ia)
            Return b2
    
    End Function
    

    Then to use it, you can simply:

    Dim b As Bitmap = New Bitmap(ofd.FileName)                        
    PictureBox1.Image = TintBitmap(b,Color.Red,0.3)