前端代碼:
<label>請輸入代碼:</label>
<br/>
<input id="barcode" class="form-control" width="100" height="30"/>
<br/>
<button id="build" class="btn-primary">生成</button>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$('#build').click(function () {
$.ajax({
url: '/Home/BuildBarcode',
type: "post",
data: { code: $('#barcode').val() },
success: function (data) {
if (data == "success") {
alert("生成成功!");
}
},
error: function () {
alert("生成失敗!");
}
});
})
</script>
後臺代碼:
public JsonResult BuildBarcode(string code)
{
System.Drawing.Image image;
int width = 250, height = 100;
byte[] buffer = GetBarcode(height, width,
BarcodeLib.TYPE.CODE128, code, out image);
return Json("success");
}
public static byte[] GetBarcode(int height, int width, BarcodeLib.TYPE type, string code, out System.Drawing.Image image)
{
image = null;
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
b.BackColor = System.Drawing.Color.White;
b.ForeColor = System.Drawing.Color.Black;
b.IncludeLabel = true;
b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
System.Drawing.Font font = new System.Drawing.Font("verdana", 10f);
b.LabelFont = font;
b.Height = height;
b.Width = width;
image = b.Encode(type, code);
SaveImage(image, code + ".png");
byte[] buffer = b.GetImageData(SaveTypes.GIF);
return buffer;
}
private static void SaveImage(System.Drawing.Image image, string p)
{
//自動保存圖片到指定目錄中
string stringfilename = "D:\\" + p;
image.Save(stringfilename, System.Drawing.Imaging.ImageFormat.Jpeg);
}
代碼下載:https://download.csdn.net/download/qq_34017733/11179202