轉(zhuǎn)載于作者Lucas汪星人:https://www.jianshu.com/p/9955b4f27501
在原先作者的基礎(chǔ)上根據(jù)我自己修改了一些代碼僅供參考:
首先需要引用NuGet包:ZXing.Net.Bindings.ZKWeb.System.Drawing
也可以使用終端開發(fā)者PowerShell使用指令安裝:dotnet add package ZXing.Net.Bindings.ZKWeb.System.Drawing
然后可以自己去寫一個(gè)Demo創(chuàng)建一個(gè)MVC控制器寫入以下代碼:
/// <summary>
/// 生成條形碼,保存成圖片,使用了ZXing
/// </summary>
public IActionResult GenerateQRimage(string content)//public static byte[] GenerateQRimage(string content)
{
//初始化條形碼格式,寬高,以及PureBarcode=true則不會留白框
var writer = new BarcodeWriterPixelData
{
Format = BarcodeFormat.CODE_128,//編碼格式CODE_128或者CODABAR
Options = new EncodingOptions { Height = 31, Width = 167, PureBarcode = true, Margin = 1 }
};
var pixelData = writer.Write(content);
using (var bitmap = new System.DrawingCore.Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb))
using (var ms = new MemoryStream())
{
var bitmapData = bitmap.LockBits(new System.DrawingCore.Rectangle(0, 0, pixelData.Width, pixelData.Height),
System.DrawingCore.Imaging.ImageLockMode.WriteOnly, System.DrawingCore.Imaging.PixelFormat.Format32bppRgb);
try
{
// we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0,
pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
// save to stream as PNG
bitmap.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png);
System.DrawingCore.Image image = System.DrawingCore.Bitmap.FromStream(ms, true);
image.Save("D:\\2010-asmart-healthcare\\SmartHealthcare\\SmartHealthcare.Web\\wwwroot\\barcodeimg\\" + content + ".png");
byte[] bytes = ms.GetBuffer();
if (bytes != null)
{
return Ok("生成成功");
}
else
{
return Ok("生成失敗");
}
}
}
在這段代碼中要注意引用的命名空間,如:System.DrawingCore 具體的情況請?jiān)谑褂玫侥愕捻?xiàng)目中去解決大概率就是命名空間的原因,還有代碼中
image.Save("D:\\2010-asmart-healthcare\\SmartHealthcare\\SmartHealthcare.Web\\wwwroot\\barcodeimg\\" + content + ".png");具體的路徑可以自己去自定義,比如可以保存到你自己的電腦文件夾中,改路徑就行了。
然后創(chuàng)建一個(gè)MVC視圖也是寫一個(gè)小Demo去測試,代碼如下:
@{
Layout = null;
}
<div>
<header>
<button id="imgOn">生成條形碼</button>
@*url: '/BarCode/GetBarCode?message=' + message + "&gifFileName=" + "D:/test/test.gif" + "&width=" + 100 + "&height=" + 50,*@
</header>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#imgOn").click(function () {
var message = "456789";
$.ajax({
url: '/BarCode/GenerateQRimage?content=' + message,
type: 'get',
success: function (res) {
console.log(res);
}
})
})
</script>
代碼中的message可以自定義條形碼中掃描出來的具體內(nèi)容 比如我在代碼中寫的456789,那么我掃描條形碼識別出來的內(nèi)容就是456789
后端接受的參數(shù)名字叫content,具體的實(shí)現(xiàn)就需要結(jié)合具體的業(yè)務(wù)。文章來源:http://www.zghlxwxcb.cn/news/detail-603103.html
然后就可以生成條形碼了。文章來源地址http://www.zghlxwxcb.cn/news/detail-603103.html
到了這里,關(guān)于使用.Net Core 生成條形碼,保存成圖片,使用ZXing的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!