C#MVC 二维码和条形码的生成与调用显示

1.二维码和条形码生成的帮助类

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.QrCode.Internal;

namespace G6.MVC.TwoCode
{
public class BaseHelper
{
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="text">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <returns></returns>
public static Bitmap CreateQr(string text, int width, int height)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true,
CharacterSet = "UTF-8", //设置内容编码
Width = width, //设置二维码的宽度和高度
Height = height,
Margin = 1//设置二维码的边距,单位不是固定像素
};

writer.Options = options;
Bitmap map = writer.Write(text);
return map;
}

/// <summary>
/// 生成一维条形码
/// </summary>
/// <param name="text">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <returns></returns>
public static Bitmap CreateBar(string text, int width, int height)
{
BarcodeWriter writer = new BarcodeWriter();
//使用ITF 格式,不能被现在常用的支付宝、微信扫出来
//如果想生成可识别的可以使用 CODE_128 格式
//writer.Format = BarcodeFormat.ITF;
writer.Format = BarcodeFormat.CODE_39;
EncodingOptions options = new EncodingOptions()
{
Width = width,
Height = height,
Margin = 2
};
writer.Options = options;
Bitmap map = writer.Write(text);
return map;
}

/// <summary>
/// 生成带Logo的二维码
/// </summary>
/// <param name="text">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
public static Bitmap CreateQrWithLogo(string text, int width, int height)
{
//Logo 图片
string logoPath = System.AppDomain.CurrentDomain.BaseDirectory + @"imglogo.png";
Bitmap logo = new Bitmap(logoPath);
//构造二维码写码器
MultiFormatWriter writer = new MultiFormatWriter();
Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//hint.Add(EncodeHintType.MARGIN, 2);//旧版本不起作用,需要手动去除白边

//生成二维码
BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width + 30, height + 30, hint);
bm = deleteWhite(bm);
BarcodeWriter barcodeWriter = new BarcodeWriter();
Bitmap map = barcodeWriter.Write(bm);

//获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
int[] rectangle = bm.getEnclosingRectangle();

//计算插入图片的大小和位置
int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width);
int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height);
int middleL = (map.Width - middleW) / 2;
int middleT = (map.Height - middleH) / 2;

Bitmap bmpimg = new Bitmap(map.Width, map.Height, 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(map, 0, 0, width, height);
//白底将二维码插入图片
g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
g.DrawImage(logo, middleL, middleT, middleW, middleH);
}
return bmpimg;
}

/// <summary>
/// 删除默认对应的空白
/// </summary>
/// <param name="matrix"></param>
/// <returns></returns>
private static BitMatrix deleteWhite(BitMatrix matrix)
{
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;

BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++)
{
for (int j = 0; j < resHeight; j++)
{
if (matrix[i + rec[0], j + rec[1]])
resMatrix[i, j] = true;
}
}
return resMatrix;
}
/// <summary>
/// 图片转换
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static string GetImgStr(Bitmap bitmap)
{
string strbaser64 = "";
try
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
strbaser64 = Convert.ToBase64String(arr);
}
return strbaser64;
}
catch (Exception ex)
{
throw new Exception("转换失败!");
}
}
}
}

2.MVC控制器调用

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace G6.MVC.TwoCode.Controllers
{
public class CodeController : Controller
{
/// <summary>
/// 显示页面
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View();
}
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="content">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <returns></returns>
[HttpGet]
public string GetQrCode(string content, int width, int height)
{
Bitmap b = BaseHelper.CreateQr(content, width, height);

return BaseHelper.GetImgStr(b);
}
/// <summary>
/// 生成条形码
/// </summary>
/// <param name="content">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <returns></returns>
[HttpGet]
public string GetBarCode(string content, int width, int height)
{
Bitmap b = BaseHelper.CreateBar(content, width, height);

return BaseHelper.GetImgStr(b);
}
}
}

3.页面Jquery代码


@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function DoQr() {
var text = $("#txt_QrStr").val();
var width = $("#txt_QrWidth").val();
var height = $("#txt_QrHeight").val();
$.get("/Code/GetQrCode", { content: text, width, height: height }, function (data) {
if (data != "") {
console.log(data);
$("#Img_QrCode").attr("src", "data:image/jgp;base64," + data)
}
else {
alert("生成失败");

}
})
}

function DoBar() {
var text = $("#txt_BarStr").val();
var width = $("#txt_BarWidth").val();
var height = $("#txt_BarHeight").val();
$.get("/Code/GetBarCode", { content: text, width, height: height }, function (data) {
if (data != "") {
console.log(data);
$("#Img_BarCode").attr("src", "data:image/jgp;base64," + data)
}
else {
alert("生成失败");

}
})
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td><img id="Img_QrCode" src="" alt="" /></td>
<td><img id="Img_BarCode" src="" alt="" /></td>
</tr>
<tr>
<td>
内容:<input id="txt_QrStr" type="text" /><br />
宽:<input id="txt_QrWidth" type="text" /><br />
高:<input id="txt_QrHeight" type="text" /><br />
<input id="btn_QrCode" type="button" value="生成二维码" onclick="DoQr()" />
</td>
<td>
内容:<input id="txt_BarStr" type="text" /><br />
宽:<input id="txt_BarWidth" type="text" /><br />
高:<input id="txt_BarHeight" type="text" /><br />
<input id="btn_BarCode" type="button" value="生成条形码" onclick="DoBar()" />
</td>
</tr>
</table>
</div>
</body>
</html>

原文地址:https://www.cnblogs.com/freedomlan/p/13184923.html