//视图
@{
Layout = null;
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="img1">
@*实现图片的盒子*@
</div>
<p>
显示文本<input type="text" id="text1" name="name1" value="" /> @*文本框*@
<input type="button" onclick="qqq()" name="name11" value="条形码生成" />@*一维码生成按钮*@
<input type="button" onclick="www()" name="name12" value="二维码生成" />@*二维码生成按钮*@
</p>
<script>
function qqq() {
var nameOne = $("#text1").val();
$.ajax({//进行Ajax 提交到控制器 (下面有控制器方法的图片)
url: '/Default/OneCode/?Name=' + nameOne ,
type: 'post',
success: function (rese) {//收到返回的一维码图片地址
$("#imge1").remove();//清空盒子中图片
$("#img1").append("<img id='images' src=" + rese + " />");//在盒子中最加二维码图片显示
}
})
}
function www() {
var nameTwo = $("#text1").val();
$.ajax({
url: '/Default/ImageCode/?Name=' + nameTwo ,
type: 'post',
success: function (rese) {
$("#imge1").remove();
$("#img1").append("<img id='images' src=" + rese + " />");
}
})
}
</script>
</body>
</html>
---------------------------------------------
//控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common; //一维码
using ZXing.QrCode; //二维码
using System.Drawing.Imaging; //图片保存
using System.Drawing;
namespace Exam_Day08.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
/// <summary>
/// 生成条形码
/// </summary>
/// <param name="Name">内容</param>
/// <returns></returns>
public string OneCode(string Name)
{
//设置条形码规格
EncodingOptions encod = new EncodingOptions();
//设置高
encod.Height = 120;
//设置宽
encod.Width = 200;
//生成条形码的图片并保存
BarcodeWriter wr = new BarcodeWriter();
//指定规格
wr.Options = encod;
//指定条形码规格为EAN_13
wr.Format = BarcodeFormat.CODE_39;
//生成图片
Bitmap img = wr.Write(Name);
//获取文件夹的绝对路径
string filepath = Server.MapPath("/image/");
if (!Directory.Exists(filepath ))
{
Directory.CreateDirectory(filepath );
}
string datime = DateTime.Now.ToString("yyMMddHHmmss");
img.Save(filepath + datime + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "/image/" + datime + ".jpg";
}
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="Name">内容</param>
/// <returns></returns>
public string ImageCode(string Name)
{
//设置二维码规格
QrCodeEncodingOptions qr = new QrCodeEncodingOptions();
//设置编码格式,否则会乱码
qr.CharacterSet = "UTF-8";
qr.Height = 200;
qr.Width = 200;
//设置二维码图片周围空白边距
qr.Margin = 1;
//生成条形码图片保存
BarcodeWriter wr = new BarcodeWriter();
//二维码
wr.Format = BarcodeFormat.QR_CODE;
wr.Options = qr;
Bitmap bit = wr.Write(Name);
//存放图片的位置,需要先创建一个image文件夹
string filepath = Server.MapPath("/image/");
if (!Directory.Exists(filepath ))
{
Directory.CreateDirectory(filepath );
}
string datime = DateTime.Now.ToString("yyMMddHHmmss");
bit.Save(filepath + datime + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "/image/" + datime + ".jpg";
}
}
}
C#生成条形码和二维码
最新推荐文章于 2024-07-30 16:13:24 发布