在网上看到一些人写关于条形码的代码都很长,有的甚至拿来卖,所以查了下资料,希望能对大家有帮助。
我的实现原理是:
其实Windows本身就有一个字体是用来显示条形码的。
只要将数字改为这种字体就变成了条形码。
windows字体库下,有如下八种字体可以用来将数字转换成条形码:
Code39AzaleaNarrow1
Code39AzaleaNarrow2
Code39AzaleaNarrow3
Code39AzaleaRegular1
Code39AzaleaRegular2
Code39AzaleaWide1
Code39AzaleaWide2
Code39AzaleaWide3
</div>
把代码贴给大家参考:
Bitmap b=new Bitmap(200,200);
Graphics g = Graphics.FromImage(b);
Font font = new Font("Code39AzaleaRegular2", 32);
g.DrawString("123456", font, Brushes.Black, new PointF(100,100));
pictureBox1.BackgroundImage = b;
pictureBox1.BackgroundImageLayout = ImageLayout.Zoom。
</div>
是不是很简单呢,亲们,思路给大家了,具体使用到项目中的时候,小伙伴们自己扩展下就可以了。
另附上一则示例中的应用
using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Drawing.Design;
using System.IO;
using System.Collections;
namespace Public.Equipment
{
/// <summary>
///绘制条形码
/// </summary>
public class DrawingBarCode
{
public DrawingBarCode()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region 根据字体产生条形码
/// <summary>
/// 根据条形码绘制图片
/// </summary>
/// <param name="strNumber">条形码</param>
public void DrawingBarCode(string strNumber)
{
PrivateFontCollection fonts = new PrivateFontCollection();
//39带数字
//fonts.AddFontFile(HttpContext.Current.Server.MapPath(".") + "/BarCodeFonts/V100010_.TTF");
//FontFamily ff = new FontFamily("C39HrP48DlTt", fonts);
//39码
strNumber = "*" + strNumber + "*";
fonts.AddFontFile(HttpContext.Current.Server.MapPath(".") + "/BarCodeFonts/FREE3OF9X.TTF");
FontFamily ff = new FontFamily("Free 3 of 9 Extended", fonts);
//接近条形码
//fonts.AddFontFile(HttpContext.Current.Server.MapPath(".") + "/BarCodeFonts/V100014_.TTF");
//FontFamily ff = new FontFamily("C39P24DlTt", fonts);
Font font = new Font(ff, 12);
//设置图片大小
Image img = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(img);
SizeF fontSize = g.MeasureString(strNumber, font);
int intWidth = Convert.ToInt32(fontSize.Width);
int intHeight = Convert.ToInt32(fontSize.Height);
g.Dispose();
img.Dispose();
img = new Bitmap(intWidth, intHeight);
g = Graphics.FromImage(img);
g.Clear(Color.White);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawString(strNumber, font, Brushes.Black, 0, 0);
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Jpeg);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "image/Jpeg";
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
g.Dispose();
img.Dispose();
}
/// <summary>
/// 根据条形码绘制图片
/// </summary>
/// <param name="strNumber">条形码</param>
/// <param name="intFontSize">字体大小</param>
public void DrawingBarCode(string strNumber,int intFontSize)
{
PrivateFontCollection fonts = new PrivateFontCollection();
&