代码之家  ›  专栏  ›  技术社区  ›  mbcrump

绘制图像后立即出现巨大的空白。想摆脱它

  •  1
  • mbcrump  · 技术社区  · 16 年前

    详情如下:

    代码项目文章链接: 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();
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Guffa    16 年前

    代码假设每个字符40像素,这就是为什么在文本的右边会有很多图像。你可以使用 MeasureString 方法来测量文本的大小,并使用该方法创建大小正确的图像:

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

    我注意到你没有处理任何你正在使用的物品。这个 Graphics , Bitmap , SolidBrush Font 需要释放对象。

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

    推荐文章