Blurry and large image barcode being generated using a plugin in Windows Form

别说谁变了你拦得住时间么 提交于 2019-12-02 04:39:41

I don't see any PlugIn reference in your code, you are just using a Code39 ASCII font to print a Barcode on a Bitmap.

The problem I see is that the size of the resulting Bitmap is unscaled.
What I mean is, you let the size of the Barcode determine the size of the final graphic image.
It is usually the opposite. You have some defined dimensions for a Bitmap, because of layout constraints: you have to print the barcode to a label, for example.
If the generated Barcode is wider than its container, you have to normalize it (scale it to fit).

Here is what I propose. The size of the Bitmap if fixed (300, 150). When the Barcode is generated, its size is scaled to fit the Bitmap size.
The quality of the image is preserved, using an Bicubic Interpolation in case of down scaling. The resulting graphics is also Anti-Aliased.
(Anti-Alias has a good visual render. May not be the best choice for printing. It also depends on the printer.)

The generated Bitmap is then passed to a PictureBox for visualization and saved to disk as a PNG image (this format because of its loss-less compression).

Here is the result:


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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!