'written by Kourosh Derakshan (MrPolite @ vbforums.com)
Imports System.Drawing.Imaging
Namespace MrPolite
Public NotInheritable Class BitmapTexture
' Please do not remove
' Written by Kourosh Derakshan
'
' Modifies the ORIGINAL bitmap
' textureTransparency has to be between 0 and 1,
' with 0 being the least transparent, and 1 the most transparent
Public Shared Sub ApplyTexture(ByVal bmp As Bitmap, _
ByVal texture As Bitmap, _
ByVal textureTransparency As Single)
If (bmp Is Nothing) OrElse (texture Is Nothing) Then Throw New ArgumentNullException
If textureTransparency < 0 OrElse textureTransparency > 1 Then
Throw New ArgumentOutOfRangeException("textureTransparency must be between 0 and 1.")
End If
' Convert the texture to grayscale before using it
MakeImageGrayscale(texture)
Dim x, y, alpha As Integer
' Adjust the alpha value of each pixel in the texture bitmap.
' The white-most pixels will have the the most transparency (highest alpha),
' and the dark-most pixels will have the least transparency.
For x = 0 To texture.Width - 1
For y = 0 To texture.Height - 1
Dim c As Color = texture.GetPixel(x, y)
' c.R -> all of the RGB values are the same since the image is in grayscale
alpha = CInt(c.R * textureTransparency)
c = Color.FromArgb(alpha, c)
texture.SetPixel(x, y, c)
Next
Next
Dim gr As Graphics = Graphics.FromImage(bmp)
Dim myBrush As New TextureBrush(texture)
' Draw the texture over the original bitmap
gr.FillRectangle(myBrush, bmp.GetBounds(GraphicsUnit.Pixel))
myBrush.Dispose()
gr.Dispose()
End Sub
' Converts the image to grayscale
Private Shared Sub MakeImageGrayscale(ByVal bmp As Bitmap)
Dim cMatrix As New ColorMatrix(New Single()() _
{New Single() {0.299, 0.299, 0.299, 0, 0}, _
New Single() {0.587, 0.587, 0.587, 0, 0}, _
New Single() {0.114, 0.114, 0.114, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}})
Dim imageAttrib As New ImageAttributes
imageAttrib.SetColorMatrix(cMatrix)
Dim gr As Graphics = Graphics.FromImage(bmp)
' Apply the grayscale image attribute
gr.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height), _
0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, imageAttrib)
gr.Dispose()
End Sub
End Class
End Namespace