首页 条码生成识别 条码生成识别示例代码 条码生成[C#]

条码生成示例代码C#

作者: 阅读数:1129 上传时间:2025-05-26

条码生成

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Barcode
{
    // 替换成你的AppKey
    private const string AppKey = "YOUR_APPKEY_HERE";

    public static async Task GenerateAsync(string Barcode, string Type="ean13", int Fontsize=12, int Dpi=72, int Scale=2, int Height=40)
    {
        try
        {
            // 构建请求 URL
            string url = $"https://api.jisuapi.com/barcode/generate?appkey={AppKey}&type={Type}&barcode={Barcode}&fontsize={FontSize}&dpi={Dpi}&scale={Scale}&height={Height}";

            using (HttpClient client = new HttpClient())
            {
                // 发送 GET 请求
                HttpResponseMessage response = await client.GetAsync(url);
                // 确保请求成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                // 解析 JSON 数据
                JObject jsonarr = JObject.Parse(responseBody);

                // 检查状态码
                if (jsonarr["status"] != null && (int)jsonarr["status"] != 0)
                {
                    if (jsonarr["msg"] != null)
                    {
                        Console.WriteLine(jsonarr["msg"]);
                    }
                    return;
                }

                // 获取结果对象
                JObject result = (JObject)jsonarr["result"];
                if (result != null)
                {
                    // 输出信息
                    Console.WriteLine($"{result["code"]} {result["fontsize"]} {result["dpi"]} {result["scale"]} {result["height"]}");

                    // 获取 Base64 编码的条形码内容
                    string content = (string)result["barcode"];

                    // 若要保存图片,可取消以下注释
                    // SaveBarcodeToFile(content, "barcode.png");

                    // 模拟输出 HTML 图片标签(控制台输出)
                    Console.WriteLine($"");
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求出错: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }

    private static void SaveBarcodeToFile(string base64Content, string filePath)
    {
        byte[] imageBytes = Convert.FromBase64String(base64Content);
        File.WriteAllBytes(filePath, imageBytes);
        Console.WriteLine($"条形码已保存到 {filePath}");
    }
	
	public static async Task Main()
    {
        // 生成条形码
        await Barcode.GenerateAsync("6901236341056");
        // 读取条形码
        await Barcode.ReadAsync("https://api.jisuapi.com/barcode/barcode/1471602033673149.png");
    }
}