使用Windows窗体中的插件生成模糊和大图像条形码

时间:2018-03-13 22:54:42

标签: c# winforms barcode barcode-printing

完成上述步骤here 并使用IDAutomationCode39,我得到条形码图像,但它们非常模糊,只扫描更大尺寸的图像。我的条形码ID最长可达30个字符,这会导致条形码图像非常宽。问题出在哪里?是下面的按钮点击事件中的IDAutomationCode39还是我的设置?

private void button1_Click(object sender, EventArgs e)
    {
        string abbre = GenerateProdCodeFromProductName();
        txt2.Text = abbre;

        string barcode = txt1.Text;

        Bitmap bitm = new Bitmap(barcode.Length * 45, 160);
        bitm.SetResolution(240, 240);
        using (Graphics graphic = Graphics.FromImage(bitm))
        {
            Font newfont = new Font("IDAutomationHC39M", 6);
            PointF point = new PointF(5f, 5f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush white = new SolidBrush(Color.White);
            graphic.FillRectangle(white, 0, 0, bitm.Width, bitm.Height);
            graphic.DrawString("*" + barcode + "*", newfont, black, point);
        }

        using (MemoryStream Mmst = new MemoryStream())
        {
            bitm.Save("ms", ImageFormat.Jpeg);
            pictureBox1.Image = bitm;
            pictureBox1.Width = bitm.Width;
            pictureBox1.Height = bitm.Height;
        }
    }

谢谢。

1 个答案:

答案 0 :(得分:0)

我在代码中看不到任何PlugIn引用,您只是使用Code39 ASCII字体在位图上打印条形码。

我看到的问题是生成的Bitmap的大小是未缩放的 我的意思是,你让条形码的大小决定最终图形图像的大小 通常情况正好相反。由于布局限制,您有一些Bitmap定义的尺寸:例如,您必须将条形码打印到标签上。
如果生成的条形码比其容器宽,则必须对其进行标准化(将其缩放以适合)。

这是我的建议。 Bitmap的大小如果固定(300,150)。生成条形码时,会缩放其大小以适合位图大小 在缩小比例的情况下,使用双立方插值保留图像的质量。生成的图形也是抗锯齿的 (Anti-Alias具有良好的视觉渲染效果。可能不是打印的最佳选择。它还取决于打印机。)

然后将生成的Bitmap传递给PictureBox进行可视化,并将其作为PNG图像保存到磁盘(由于其无损压缩,这种格式)。

结果如下:

enter image description here

string Barcode = "*8457QK3P9*";

using (Bitmap bitmap = new Bitmap(300, 150))
{
    bitmap.SetResolution(240, 240);
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        Font font = new Font("IDAutomationSHC39M", 10, FontStyle.Regular, GraphicsUnit.Point);

        graphics.Clear(Color.White);
        StringFormat stringformat = new StringFormat(StringFormatFlags.NoWrap);
        graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
        graphics.TextContrast = 10;

        PointF TextPosition = new PointF(10F, 10F);
        SizeF TextSize = graphics.MeasureString(Barcode, font, TextPosition, stringformat);

        if (TextSize.Width > bitmap.Width)
        {
            float ScaleFactor = (bitmap.Width - (TextPosition.X / 2)) / TextSize.Width;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.ScaleTransform(ScaleFactor, ScaleFactor);
        }

        graphics.DrawString(Barcode, font, new SolidBrush(Color.Black), TextPosition, StringFormat.GenericTypographic);

        bitmap.Save(@"[SomePath]\[SomeName].png", ImageFormat.Png);
        this.pictureBox1.Image = (Bitmap)bitmap.Clone();
        font.Dispose();
    }
}
相关问题