2010-07-23 12 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