从字体Free 3 of 9创建条形码

时间:2013-07-24 09:49:51

标签: c# .net barcode

这是我创建条形码图片的代码:

 class Program
    {
        static void Main(string[] args)
        {
            CreateBarcode("The quick brown fox jumps over the lazy dog".ToUpper());

        }

        private static void CreateBarcode(string code)
        {
            var myBitmap = new Bitmap(500, 50);
            var g = Graphics.FromImage(myBitmap);
            var jgpEncoder = GetEncoder(ImageFormat.Jpeg);

            g.Clear(Color.White);

            var strFormat = new StringFormat { Alignment = StringAlignment.Center };
            g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);

            var myEncoder = Encoder.Quality;
            var myEncoderParameters = new EncoderParameters(1);

            var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            //MemoryStream memoryStrem = new 
            myBitmap.Save(@"d:\Barcode.jpg", jgpEncoder, myEncoderParameters);
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();

            foreach (var codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        } 

    }

但是,这行正常:g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);

你可以看到这里的宽度是500.现在,如果我指定一段大文本,我担心500这是不够的。有没有办法根据内容使这个宽度动态化?

1 个答案:

答案 0 :(得分:0)

它太老了,无法回答,仍然在发帖,因为它可能对某人有所帮助。我们可以使用虚拟位图创建图形对象,然后尝试查找字体长度,然后重新初始化位图以及图形对象。

var myBitmap = new Bitmap(1, 1);
Font threeOfNine = new Font("Free 3 of 9", 60, FontStyle.Regular, GraphicsUnit.Point);
var g = Graphics.FromImage(myBitmap);
SizeF dataSize = g.MeasureString(code, threeOfNine);
myBitmap = new Bitmap(myBitmap, dataSize.ToSize());
g = Graphics.FromImage(myBitmap);