1. 程式人生 > >QR二維碼生成器原始碼(中間可插入小圖片)

QR二維碼生成器原始碼(中間可插入小圖片)

//構造二維碼寫碼器 MultiFormatWriter mutiWriter = new com.google.zxing.MultiFormatWriter(); Hashtable hint=new Hashtable(); hint.Add(EncodeHintType.CHARACTER_SET,"UTF-8"); hint.Add(EncodeHintType.ERROR_CORRECTION,com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
//生成二維碼 ByteMatrix bm = mutiWriter.encode(txtMsg.Text, com.google.zxing.BarcodeFormat.QR_CODE, 300, 300,hint); Bitmap img = bm.ToBitmap(); //要插入到二維碼中的圖片 Image middlImg = QRMiddleImg.Image; //獲取二維碼實際尺寸(去掉二維碼兩邊空白後的實際尺寸) System.Drawing.Size realSize = mutiWriter.GetEncodeSize(txtMsg.Text, com.google.zxing.BarcodeFormat.QR_CODE, 300
, 300); //計算插入圖片的大小和位置 int middleImgW = Math.Min((int)(realSize.Width / 3.5), middlImg.Width); int middleImgH = Math.Min((int)(realSize.Height / 3.5),middlImg.Height); int middleImgL = (img.Width - middleImgW) / 2; int middleImgT = (img.Height - middleImgH) / 2
; //將img轉換成bmp格式,否則後面無法建立 Graphics物件 Bitmap bmpimg = new Bitmap(img.Width, img.Height,System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmpimg)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.DrawImage(img, 0, 0); } //在二維碼中插入圖片 System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(bmpimg); //白底 MyGraphic.FillRectangle(Brushes.White,middleImgL, middleImgT, middleImgW, middleImgH); MyGraphic.DrawImage(middlImg, middleImgL, middleImgT, middleImgW, middleImgH); pictureBox1.Image = bmpimg; //自動儲存圖片到當前目錄 string filename = System.Environment.CurrentDirectory + "\\QR" + DateTime.Now.Ticks.ToString() + ".jpg"; bmpimg.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg); lbshow.Text = "圖片已儲存到:" + filename;