WPF 使用QRCoder生成二维码

2021-07-02 13:10

阅读:559

标签:format   efi   empty   options   end   pen   open   aml   nfx   

vs中使用Nuget获取QRCoder

技术分享图片

窗体中添加按钮和Iage

Window x:Class="QRCoderTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:QRCoderTest"
        xmlns:qr="clr-namespace:QRCoder;assembly=QRCoder"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    Grid>
        Grid.ColumnDefinitions>
            ColumnDefinition  Width="0.3*"/>
            ColumnDefinition Width="0.7*"/>
        Grid.ColumnDefinitions>
        Button Content="Button" HorizontalAlignment="Left" Margin="51,90,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        Image x:Name="img" Grid.Column="1"/>
    Grid>
Window>

后台代码

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CreateQR(100,"aaa123!ly是是是@#¥%……",System.Drawing.Color.Black,System.Drawing.Color.White,new Bitmap(@"E:\Work\ly\MES图片\1.png"));
        }

        private void CreateQR(int pixelsPerModule, string info, System.Drawing.Color qrColor, System.Drawing.Color qrBackgroundColor, Bitmap logo, int iconSizePercent = 15, int iconBorderWidth = 6)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(info, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(pixelsPerModule, qrColor, qrBackgroundColor, logo, iconSizePercent, iconBorderWidth, true);


            IntPtr hBitmap = qrCodeImage.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            img.Source = wpfBitmap;
        }
    }

QRCoder生成的是Bitmap,在WPF中需要转换为ImageSource。

运行程序

技术分享图片

生成成功。

WPF 使用QRCoder生成二维码

标签:format   efi   empty   options   end   pen   open   aml   nfx   

原文地址:https://www.cnblogs.com/czly/p/9923226.html


评论


亲,登录后才可以留言!