2010-07-23 10 views
1

我正在使用下面的代码项目来建立一个asp.net网站,迄今为止一切都很好。我唯一的问题是在生成条形码之后,条形码右侧存在巨大的空白。我一直在玩这个,我无法解决它。下面在绘制图像后存在巨大的空白。想摆脱它

详情:

链接代码项目文章:http://www.codeproject.com/KB/aspnet/AspBarCodes.aspx?msg=3543809

字体的复制是在这里:http://trussvillemethodist.web01.appliedi-labs.net/IDAutomationHC39M.ttf

  //Working Path 
     string sWorkPath = ""; 
     sWorkPath = this.Context.Server.MapPath(""); 

     //Fonts 
     PrivateFontCollection fnts = new PrivateFontCollection(); 
     fnts.AddFontFile(sWorkPath + @"\IDAutomationHC39M.ttf"); 
     FontFamily fntfam = new FontFamily("IDAutomationHC39M", fnts); 
     Font oFont = new Font(fntfam, 18); 

     // Get the Requested code sent from the previous page. 
     string strCode = Request["code"].ToString(); 

     //Graphics 
     //I don't know what to set the width to as I can't call the MeasureString without creating the Graphics object. 
     Bitmap oBitmaptemp = new Bitmap(40, 100); 
     Graphics oGraphicstemp = Graphics.FromImage(oBitmaptemp); 
     int w = (int)oGraphicstemp.MeasureString(strCode, oFont).Width + 4; 

     // Create a bitmap object of the width that we calculated and height of 100 
     Bitmap oBitmap = new Bitmap(w, 100); 

     // then create a Graphic object for the bitmap we just created. 
     Graphics oGraphics = Graphics.FromImage(oBitmap); 

     // Let's create the Point and Brushes for the barcode 
     PointF oPoint = new PointF(2f, 2f); 
     SolidBrush oBrushWrite = new SolidBrush(Color.Black); 
     SolidBrush oBrush = new SolidBrush(Color.White); 

     // Now lets create the actual barcode image 
     // with a rectangle filled with white color 
     oGraphics.FillRectangle(oBrush, 0, 0, w, 100); 

     // We have to put prefix and sufix of an asterisk (*), 
     // in order to be a valid barcode 
     oGraphics.DrawString("*" + strCode + "*", oFont, oBrushWrite, oPoint); 

     // Then we send the Graphics with the actual barcode 
     Response.ContentType = "image/gif"; 
     oBitmap.Save(Response.OutputStream, ImageFormat.Gif); 

     oBitmap.Dispose(); 
     oGraphics.Dispose(); 
     oBrush.Dispose(); 
     oFont.Dispose(); 

回答

3

的代码只是假定每个字符的40个像素,这就是为什么你在文本右侧留下很多图像。您可以使用MeasureString方法来测量文本的大小,并用它来创建正确尺寸的图像:

int w = (int)oGraphics.MeasureString("*123$10.00*", oFont).Width + 4; 

我注意到,你不处理任何你正在使用的对象。需要处理的对象有Graphics,Bitmap,SolidBrushFont

您可能还想考虑使用GIF图像而不是JPEG,它更适合这种图形。

+0

对不起,你可以拼出来给我。我无法调用oGraphics或oFont,因为它尚未实例化。我也将“int w”向下移动,因为它用于创建Bitmap对象。 “代码”字符串来自something.aspx?代码= 123 $ 2.00 – mbcrump 2010-07-23 18:39:48

+1

您的代码也隐式地将类型'System.Drawing.SizeF'转换为'int',这是不允许的。任何帮助表示赞赏。 – mbcrump 2010-07-23 18:58:15

+0

@mbcrump:使用的过载只有两个参数,之后添加'4',这不是第三个参数。 – Guffa 2010-07-23 19:02:44