需要zxing库支持ZXing.NET Generate QR Code & Barcode in C# Alternatives | IronBarcode
效果图:
思路:先生成1个单位的二维码,然后再通过像素填充颜色,颜色数组要通过洗牌算法
洗牌算法
Dim shuffledCards As New List(Of Color)
Sub GenColor()
shuffledCards.Clear()
Dim cards() = {Color.Red, Color.Blue, Color.Green, Color.Black, Color.Brown}
For i = 0 To 40
shuffledCards.AddRange(ShuffleArray(cards))
Next
End Sub
' Fisher-Yates洗牌算法实现
Function ShuffleArray(ByVal array() As Color) As Color()
Dim currentIndex As Integer = array.Length
Dim random As New Random()
' 当还剩有元素未洗牌时
While currentIndex > 0
' 选取一个0到currentIndex之间的随机索引
Dim randomIndex As Integer = random.Next(currentIndex)
currentIndex -= 1
' 交换当前元素和随机索引处的元素
Dim temp As Color = array(currentIndex)
array(currentIndex) = array(randomIndex)
array(randomIndex) = temp
End While
' 返回洗牌后的数组
Return array
End Function
色块识别、填充算法(二维码的生成):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim qr = New Bitmap(GenByZXingNet_Color(Content.Text))
If CBRandColor.Checked = True Then
GenColor()
Dim k As Integer
For i = 0 To qr.Height - 1
For j = 0 To qr.Width - 1
Dim c = qr.GetPixel(j, i)
If CInt(c.R) + CInt(c.G) + CInt(c.B) = 0 Then
qr.SetPixel(j, i, shuffledCards(k))
End If
k += 1
If k > shuffledCards.Count - 1 Then
k = 0
End If
Next
Next
End If
Dim zk As Integer = CInt(ZoomK.Value)
Dim NewQr = New Bitmap(qr.Width * zk, qr.Height * zk)
For i = 0 To qr.Height - 1
For j = 0 To qr.Width - 1
Dim c = qr.GetPixel(j, i)
Dim g = Graphics.FromImage(NewQr)
g.FillRectangle(New SolidBrush(c), New Rectangle(j * zk, i * zk, zk, zk))
Next
Next
DestImg.Image = NewQr
End Sub
Public Shared Function GenByZXingNet_Color(ByVal msg As String, ByVal Optional codeSizeInPixels As Integer = 250) As Bitmap
Dim writer As BarcodeWriter = New BarcodeWriter()
'writer.Renderer = New ZXing.Rendering.BitmapRenderer With {
' .Background = Color.White,
' .Foreground = Color.Black
' }
writer.Format = BarcodeFormat.QR_CODE
'writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8")
'writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H)
writer.Options.Height = 1
writer.Options.Width = 1
writer.Options.Margin = 0
Dim img As Bitmap = writer.Write(msg)
Return img
End Function
条形码的生成
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim options = New ZXing.Common.EncodingOptions()
'options.Height = 120
'options.Width = 200
Dim Writer = New ZXing.BarcodeWriter()
'writer.Options = options
Writer.Format = ZXing.BarcodeFormat.CODE_128
Dim qr = Writer.Write(Content.Text)
DestImg.Image = qr
End Sub
保存
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim save As New SaveFileDialog
save.Filter = "PNG File|*.png|JPG File|*.jpg|BMP File|*.bmp|All File|*.*"
save.Title = "选择保存位置"
save.FileName = Content.Text
If save.ShowDialog() = DialogResult.OK Then
DestImg.Image.Save(save.FileName)
End If
End Sub