需要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.ClickDim qr = New Bitmap(GenByZXingNet_Color(Content.Text))If CBRandColor.Checked = True ThenGenColor()Dim k As IntegerFor i = 0 To qr.Height - 1For j = 0 To qr.Width - 1Dim c = qr.GetPixel(j, i)If CInt(c.R) + CInt(c.G) + CInt(c.B) = 0 Thenqr.SetPixel(j, i, shuffledCards(k))End Ifk += 1If k > shuffledCards.Count - 1 Thenk = 0End IfNextNextEnd IfDim zk As Integer = CInt(ZoomK.Value)Dim NewQr = New Bitmap(qr.Width * zk, qr.Height * zk)For i = 0 To qr.Height - 1For j = 0 To qr.Width - 1Dim c = qr.GetPixel(j, i)Dim g = Graphics.FromImage(NewQr)g.FillRectangle(New SolidBrush(c), New Rectangle(j * zk, i * zk, zk, zk))NextNextDestImg.Image = NewQrEnd SubPublic Shared Function GenByZXingNet_Color(ByVal msg As String, ByVal Optional codeSizeInPixels As Integer = 250) As BitmapDim 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 = 1writer.Options.Width = 1writer.Options.Margin = 0Dim img As Bitmap = writer.Write(msg)Return imgEnd Function

条形码的生成

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.ClickDim options = New ZXing.Common.EncodingOptions()'options.Height = 120'options.Width = 200Dim Writer = New ZXing.BarcodeWriter()'writer.Options = optionsWriter.Format = ZXing.BarcodeFormat.CODE_128Dim qr = Writer.Write(Content.Text)DestImg.Image = qrEnd Sub

保存

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.ClickDim save As New SaveFileDialogsave.Filter = "PNG File|*.png|JPG File|*.jpg|BMP File|*.bmp|All File|*.*"save.Title = "选择保存位置"save.FileName = Content.TextIf save.ShowDialog() = DialogResult.OK ThenDestImg.Image.Save(save.FileName)End IfEnd Sub