引用类库Gma.QrCodeNet.EnCodeing
主要代码:
CreateQrCode类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 5 namespace _2DCodeCA 6 { 7 using System.IO; 8 using Gma.QrCodeNet.Encoding; 9 using Gma.QrCodeNet.Encoding.Windows.Render; 10 using System.Drawing.Imaging; 11 using System.Drawing; 12 using System.Drawing.Drawing2D; 13 public class CreateQrCode 14 { 15 public Image Create(string text) 16 { 17 QrCode code; 18 QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H); 19 Image img = null; 20 if (encoder.TryEncode(text, out code)) 21 { 22 var render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two)); 23 using (MemoryStream ms = new MemoryStream()) 24 { 25 render.WriteToStream(code.Matrix, ImageFormat.Png, ms); 26 img = Image.FromStream(ms); 27 } 28 } 29 return img; 30 } 31 32 public Image ReviceImage(Image img, int nWidth, int nHeight) 33 { 34 Image b = new Bitmap(nWidth, nHeight); 35 using (Graphics graphics = Graphics.FromImage(b)) 36 { 37 38 graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 39 graphics.DrawImage(img, new Rectangle(0, 0, nWidth, nHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); 40 } 41 return img; 42 } 43 44 public Image Create(string text, string logoPath) 45 { 46 Image imgLogo = Image.FromFile(logoPath); 47 Image img=Create(text); 48 if (imgLogo.Width != 65 || imgLogo.Height != 65) 49 { 50 imgLogo = ReviceImage(imgLogo, 65, 65); 51 } 52 Graphics graphics = Graphics.FromImage(img); 53 graphics.DrawImage(imgLogo, img.Width / 2 - imgLogo.Width / 2, img.Width / 2 - imgLogo.Width / 2, imgLogo.Width, imgLogo.Height); 54 return img; 55 } 56 } 57 }
界面代码:
1 private void btnCreate_Click(object sender, EventArgs e) 2 { 3 string str = "姓名:" + txtName.Text + "\n号码:" + txtPhone.Text + "\n性别:" + txtSex.Text; 4 CreateQrCode create=new CreateQrCode(); 5 if (string.IsNullOrWhiteSpace(txtPath.Text)) 6 { 7 img2DCode.Image = create.Create(str); 8 } 9 else 10 { 11 img2DCode.Image = create.Create(str, txtPath.Text); 12 } 13 14 } 15 16 private void btnPath_Click(object sender, EventArgs e) 17 { 18 OpenFileDialog open = new OpenFileDialog(); 19 open.ShowDialog(); 20 txtPath.Text = open.FileName; 21 }
效果图:
文章引用:http://www.tuicool.com/articles/f6ruei
类库下载:http://www.qrcode-generator.com/
时间: 2024-10-13 19:50:25