You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从显示条形码的PictureBox保存图片?附条形码生成代码

实现PictureBox中条形码图片的本地保存功能

保存功能实现代码

添加一个保存按钮(命名为Save_Barcode),并编写如下点击事件:

private void Save_Barcode_Click(object sender, EventArgs e)
{
    // 检查PictureBox是否有可保存的图片
    if (Barcode_Result.Image == null)
    {
        MessageBox.Show("无可用条形码图片可保存!");
        return;
    }

    using (SaveFileDialog saveDialog = new SaveFileDialog())
    {
        // 设置支持的保存格式
        saveDialog.Filter = "PNG 图片 (*.png)|*.png|JPEG 图片 (*.jpg)|*.jpg|所有文件 (*.*)|*.*";
        saveDialog.DefaultExt = "png";
        // 以输入的条形码内容作为默认文件名
        saveDialog.FileName = $"Barcode_{textBox1.Text}";

        if (saveDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // 根据选择的扩展名确定保存格式
                ImageFormat saveFormat = ImageFormat.Png;
                if (saveDialog.FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                {
                    saveFormat = ImageFormat.Jpeg;
                }
                // 执行保存操作
                Barcode_Result.Image.Save(saveDialog.FileName, saveFormat);
                MessageBox.Show("图片保存成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败:{ex.Message}");
            }
        }
    }
}

关键注意事项

  • 保存前必须判断Barcode_Result.Image是否为null,避免空引用异常
  • 使用SaveFileDialog让用户自主选择保存路径和格式,提升交互体验
  • 加入异常捕获逻辑,处理权限不足、路径无效等潜在错误
  • 需确保项目已引用System.Windows.Forms和System.Drawing.Imaging命名空间

原生成条形码代码(带中文注释)

private void Generate_Barcode_Click(object sender, EventArgs e)
{
    string barcode = textBox1.Text;
    // 创建对应尺寸的Bitmap对象,用于绘制条形码
    Bitmap bitmap = new Bitmap(barcode.Length * 40, 150);
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        // 使用Code39码专用字体
        Font ofont = new System.Drawing.Font("IDAutomationHC39M Free Version", 20);
        PointF point = new PointF(2f, 2f);
        SolidBrush black = new SolidBrush(Color.Black);
        SolidBrush white = new SolidBrush(Color.White);
        // 绘制白色背景
        graphics.FillRectangle(white, 0, 0, bitmap.Width, bitmap.Height);
        // Code39码要求前后加*作为起止标识
        graphics.DrawString("*" + barcode + "*", ofont, black, point);
    }
    using (MemoryStream ms = new MemoryStream())
    {
        bitmap.Save(ms, ImageFormat.Png);
        // 将生成的图片绑定到PictureBox控件
        Barcode_Result.Image = bitmap;
        // 调整PictureBox尺寸匹配图片大小
        Barcode_Result.Height = bitmap.Height;
        Barcode_Result.Width = bitmap.Width;
    }
}

内容的提问来源于stack exchange,提问作者Justine Louise Villa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:20:48