在现有图像上书写文字
Writing text on existing image
我正在尝试编写一些 ASP.NET 页面的脚本,该页面将获取现有图像并向其中添加文本。然后我希望图像(带有文本)像 .png 页面一样显示在页面中,以便可以在论坛等中加载。
这是我目前的代码:
Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath("~/Images/sigbg.png"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString("Test", new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold), SystemBrushes.WindowText, 0,0);
graphicImage.DrawArc(new Pen(Color.Red, 3), 0, 0, 150, 50, 0, 360);
Response.ContentType = "image/png";
bitMapImage.Save(Response.OutputStream, ImageFormat.Png);
graphicImage.Dispose();
bitMapImage.Dispose();
遗憾的是,它没有将文本添加到图像并将其保存为原始图像。然后页面显示 "new" 图像但没有文本。如何解决?
您的代码正确并在左上角输出 "test" 和一个椭圆。确保 page/image 未被缓存。例如,如果您将代码放在 aspx 页面中,然后尝试使用随机查询调用该页面,即 "image.aspx?12345" 或清除浏览器中的缓存。
您也可以尝试添加以下代码来避免缓存
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
我正在尝试编写一些 ASP.NET 页面的脚本,该页面将获取现有图像并向其中添加文本。然后我希望图像(带有文本)像 .png 页面一样显示在页面中,以便可以在论坛等中加载。 这是我目前的代码:
Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath("~/Images/sigbg.png"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString("Test", new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold), SystemBrushes.WindowText, 0,0);
graphicImage.DrawArc(new Pen(Color.Red, 3), 0, 0, 150, 50, 0, 360);
Response.ContentType = "image/png";
bitMapImage.Save(Response.OutputStream, ImageFormat.Png);
graphicImage.Dispose();
bitMapImage.Dispose();
遗憾的是,它没有将文本添加到图像并将其保存为原始图像。然后页面显示 "new" 图像但没有文本。如何解决?
您的代码正确并在左上角输出 "test" 和一个椭圆。确保 page/image 未被缓存。例如,如果您将代码放在 aspx 页面中,然后尝试使用随机查询调用该页面,即 "image.aspx?12345" 或清除浏览器中的缓存。
您也可以尝试添加以下代码来避免缓存
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();