Imports System.Drawing.Imaging
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim orgImage As Bitmap = PictureBox1.Image '~~~ original image
Dim maskImage As Bitmap = TextImageFiller.Fill("akhileshbc", PictureBox1.Size, Me.Font, Color.White, Color.Black) '~~~ generating the mask by passing the text, size of image, fontcolor (should be white as we are using this for comparison) and backcolor (any color other than white)
Dim compImage As New Bitmap(orgImage.Width, orgImage.Height) '~~~ final image
'~~~ prepare the final image's background (ie. create a black background)
Using g As Graphics = Graphics.FromImage(compImage)
g.FillRectangle(Brushes.Black, 0, 0, orgImage.Width, orgImage.Height)
End Using
'~~~ loop through the pixels, compare the colors of the mask image and put color based on the mask.
For i As Integer = 0 To maskImage.Width - 1
For j As Integer = 0 To maskImage.Height - 1
'~~~ if the mask image's current pixel's color is white and not transparent (in case of PNG images), then put that color in the final image's pixel position
If maskImage.GetPixel(i, j) = Color.FromArgb(255, Color.White) AndAlso orgImage.GetPixel(i, j) <> Color.FromArgb(0, 0, 0, 0) Then
compImage.SetPixel(i, j, orgImage.GetPixel(i, j)) '~~~ put the original color
ElseIf orgImage.GetPixel(i, j) = Color.FromArgb(0, 0, 0, 0) Then '~~~ check if it is transparent color
compImage.SetPixel(i, j, Color.FromArgb(0, 0, 0, 0)) '~~~ put the transparent color
End If
Next
Next
'~~~ display the output
Me.PictureBox2.Image = compImage
End Sub
End Class
'~~~ the following code is provided by ForumAccount
'~~~ Thanks to him :)
Public Class TextImageFiller
'//methods
Public Shared Function Fill(ByVal text As String, _
ByVal imageSize As Size, ByVal font As Font) As Bitmap
Return TextImageFiller.Fill(text, imageSize, font, Color.Black)
End Function
Public Shared Function Fill(ByVal text As String, ByVal imageSize As Size, _
ByVal font As Font, ByVal fontColor As Color) As Bitmap
Return TextImageFiller.Fill(text, imageSize, font, fontColor, Color.White)
End Function
Public Shared Function Fill(ByVal text As String, ByVal imageSize As Size, _
ByVal font As Font, ByVal fontColor As Color, _
ByVal backColor As Color) As Bitmap
Dim bmp = New Bitmap(imageSize.Width, imageSize.Height)
Using g = Graphics.FromImage(bmp)
Dim flags = TextFormatFlags.NoPadding
Dim sz = TextRenderer.MeasureText(g, text, font, Size.empty, flags)
For x = 0 To bmp.Width - 1 Step sz.Width
For y = 0 To bmp.Height - 1 Step sz.Height
TextRenderer.DrawText(g, text, font, New Point(x, y), _
fontColor, backColor, flags)
Next
Next
End Using
Return bmp
End Function
End Class