用ZXing.net生成条形码 [英] Generate barcode with ZXing.net
问题描述
我正在尝试使用ZXing.NET为点网核心asp.net应用程序生成条形码.我不知道如何用条形码显示文本,而且文档似乎真的很缺乏.有谁知道如何使它工作?
I'm trying to generate a barcode using ZXing.NET for dot net core asp.net application. I can't figure out how to display text with the barcode and documentation seems to be really, really lacking. Does anyone have an idea how to make it work?
这是我拥有的代码(大部分取自SO上的另一篇文章):
This is the code I have (mostly taken from another post on SO):
BarcodeWriterPixelData writer = new BarcodeWriterPixelData()
{
Format = BarcodeFormat.CODE_128,
Options = new EncodingOptions
{
Height = 400,
Width = 800,
PureBarcode = false, // this should indicate that the text should be displayed, in theory. Makes no difference, though.
Margin = 10
}
};
var pixelData = writer.Write("test text");
using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
using (var ms = new System.IO.MemoryStream())
{
var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
try
{
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return File(ms.ToArray(), "image/jpeg");
}
}
这会给我一个条形码,但没有内容.
This gets me a barcode, but no content.
或者,更好/更易于使用/文档更好的库的建议也将受到赞赏.
Or, suggestions of better/easier to use/better-documented libraries would be appreciated too.
推荐答案
您无需手动将这些像素数据复制到另一个流中.始终喜欢使用接口提供的方法,即 Save()
方法.
You don't need to copy those pixels data to another stream manually. Always prefer to using methods provided by the interface , namely the Save()
method.
public void YourActionMethod()
{
BarcodeWriter writer = new BarcodeWriter(){
Format = BarcodeFormat.CODE_128,
Options = new EncodingOptions {
Height = 400,
Width = 800,
PureBarcode = false,
Margin = 10,
},
};
var bitmap = writer.Write("test text");
bitmap.Save(HttpContext.Response.Body,System.Drawing.Imaging.ImageFormat.Png);
return; // there's no need to return a `FileContentResult` by `File(...);`
}
演示:
这篇关于用ZXing.net生成条形码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!