字符串生成条形码图片C#代码
/// 字符串生成条形码图片C#代码
/// </summary>
/// <param name="barCode">条形码字符串</param>
/// <returns></returns>
public Bitmap GenerateBarcode(string barCode)
{
int bcodeWidth = 0;
int bcodeHeight = 0;
// 得到空白图片
Bitmap bcodeBitmap = CreateImageContainer(barCode, ref bcodeWidth, ref bcodeHeight);
Graphics objGraphics = Graphics.FromImage(bcodeBitmap);
// 填充背景颜色
objGraphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bcodeWidth, bcodeHeight));
int vpos = 0;
// 画标题
if (titleString != null)
{
objGraphics.DrawString(titleString, titleFont, new SolidBrush(Color.Black), XCentered((int)titleSize.Width, bcodeWidth), vpos);
vpos += (((int)titleSize.Height) + itemSepHeight);
}
// 画条码
objGraphics.DrawString(barCode, Code39Font, new SolidBrush(Color.Black), XCentered((int)barCodeSize.Width, bcodeWidth), vpos);
// 画条码字符串
if (showCodeString)
{
vpos += (((int)barCodeSize.Height));
objGraphics.DrawString(barCode, codeStringFont, new SolidBrush(Color.Black), XCentered((int)codeStringSize.Width, bcodeWidth), vpos);
}
//返回条码图片
return bcodeBitmap;
}
/// <summary>
/// 建立指定大小的空白图片
/// </summary>
/// <param name="barCode">条码字符串</param>
/// <param name="bcodeWidth">宽度</param>
/// <param name="bcodeHeight">高度</param>
/// <returns></returns>
private Bitmap CreateImageContainer(string barCode, ref int bcodeWidth, ref int bcodeHeight)
{
Graphics objGraphics;
//建立临时图片
Bitmap tmpBitmap = new Bitmap(1, 1, PixelFormat.Format64bppPArgb);
objGraphics = Graphics.FromImage(tmpBitmap);
// 计算标题size
if (!string.IsNullOrEmpty(titleString))
{
titleSize = objGraphics.MeasureString(titleString, titleFont);
bcodeWidth = (int)titleSize.Width;
bcodeHeight = (int)titleSize.Height + itemSepHeight;
}
//计算条码size
barCodeSize = objGraphics.MeasureString(barCode, Code39Font);
bcodeWidth = Max(bcodeWidth, (int)barCodeSize.Width);
bcodeHeight += (int)barCodeSize.Height;
//计算条码字符串size
if (showCodeString)
{
codeStringSize = objGraphics.MeasureString(barCode, codeStringFont);
bcodeWidth = Max(bcodeWidth, (int)codeStringSize.Width);
bcodeHeight += (itemSepHeight + (int)codeStringSize.Height);
}
//释放资源
objGraphics.Dispose();
tmpBitmap.Dispose();
return (new Bitmap(bcodeWidth, bcodeHeight, PixelFormat.Format32bppArgb));
}
原文链接:http://www.jxszl.com/biancheng/C/556427.html