绘制图像后右侧存在巨大的空白。想要摆脱它
我正在使用以下代码项目来构建一个 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码仅假设每个字符 40 个像素,这就是为什么文本右侧会留下大量图像的原因。您可以使用 MeasureString 方法来测量文本的大小,并使用它来创建正确大小的图像:
我注意到您没有处置正在使用的任何对象。需要处理
Graphics
、Bitmap
、SolidBrush
和Font
对象。您可能还想考虑使用 GIF 图像而不是 JPEG,它更适合此类图形。
The code just assumes 40 pixels per character, which is why you get a lot of image left on the right of the text. You can use the
MeasureString
method to measure the size of the text, and use that to create an image of the correct size:I noticed that you don't dispose any of the objects that you are using. The
Graphics
,Bitmap
,SolidBrush
andFont
objects need to be disposed.You might also want to consider using a GIF image instead of JPEG, it's more suited for this kind of graphics.