赞
踩
1.指定大小文本生成二维码
- private Bitmap GetQRCodeByZXingNet(String strMessage, Int32 width, Int32 height)
- {
- Bitmap result = null;
- try
- {
- BarcodeWriter barCodeWriter = new BarcodeWriter();
- barCodeWriter.Format = BarcodeFormat.QR_CODE;
- barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
- barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
- barCodeWriter.Options.Height = height;
- barCodeWriter.Options.Width = width;
- barCodeWriter.Options.Margin = 0;
- BitMatrix bm = barCodeWriter.Encode(strMessage);
- result = barCodeWriter.Write(bm);
- }
- catch (Exception ex)
- {
- //异常输出
- }
- return result;
- }
2.生成中间带特定图标的二维码
- public static Bitmap GeneratorQrImage(string contents, Image middleImg, int width = 300, int height = 300)
- {
- try
- {
- //构造二维码写码器
- MultiFormatWriter mutiWriter = new MultiFormatWriter();
- Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
- hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
- hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
-
- //生成二维码
- BitMatrix bm = mutiWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hint);
- BarcodeWriter barcodeWriter = new BarcodeWriter();
- Bitmap bitmap = barcodeWriter.Write(bm);
-
- //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
- int[] rectangle = bm.getEnclosingRectangle();
-
- //计算插入图片的大小和位置
- int middleImgW = Math.Min((int)(rectangle[2] / 3.5), middleImg.Width);
- int middleImgH = Math.Min((int)(rectangle[3] / 3.5), middleImg.Height);
- int middleImgL = (bitmap.Width - middleImgW) / 2;
- int middleImgT = (bitmap.Height - middleImgH) / 2;
-
- //将img转换成bmp格式,否则后面无法创建 Graphics对象
- Bitmap bmpimg = new Bitmap(bitmap.Width, bitmap.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(bitmap, 0, 0);
- }
-
- //在二维码中插入图片
- Graphics myGraphic = Graphics.FromImage(bmpimg);
- //白底
- myGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
- myGraphic.DrawImage(middleImg, middleImgL, middleImgT, middleImgW, middleImgH);
- return bmpimg;
- }
- catch (Exception ex)
- {
- //异常输出
- }
- return null;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。