Loading

C# 生成条形码(ZXing.Net)

1、通过Nuget包添加ZXing.Net引用

        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="filePath">生成条形码保存地址</param>
        /// <param name="barCodeContent">条形码内容</param>
        public static void CreateBarCode(string filePath, string barCodeContent)
        {
            ZXing.Common.EncodingOptions options = new ZXing.Common.EncodingOptions()
            {
                Height = 120,//设置宽高
                Width = 200,
            };
            //生成条形码的图片并保存
            ZXing.BarcodeWriter wr = new ZXing.BarcodeWriter()
            {
                Options = options,//进行指定规格
                Format = ZXing.BarcodeFormat.CODE_128,//条形码的规格
            };
            System.Drawing.Bitmap img = wr.Write(barCodeContent);//生成图片
            img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            System.Diagnostics.Process.Start(filePath);
        }
        /// <summary>
        /// 读取条形码
        /// </summary>
        /// <param name="filePath">读取的条形码地址</param>
        /// <returns></returns>
        public static string ReadBarCode(string filePath)
        {
            //设置读取规格
            ZXing.Common.DecodingOptions options = new ZXing.Common.DecodingOptions();
            options.PossibleFormats = new System.Collections.Generic.List<ZXing.BarcodeFormat>()
            {
                ZXing.BarcodeFormat.CODE_128,//指定格式
            };
            //读取
            ZXing.BarcodeReader br = new ZXing.BarcodeReader() { Options = options };
            System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
            //读取条形码内容
            ZXing.Result result = br.Decode(image as System.Drawing.Bitmap);
            return result.Text;
        }

结果如下:

 参考文章:C# WinForm生成二维码,一维码,条形码 操作 - C#的南墙 - 博客园 (cnblogs.com)

posted @ 2023-05-05 15:06  流纹  阅读(1265)  评论(2编辑  收藏  举报