65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 动态生成图像

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (4投票s)

2010年7月10日

CPOL

1分钟阅读

viewsIcon

32686

downloadIcon

415

本文是对如何在 ASP.NET Web 应用程序中动态生成图像的快速描述。

引言

在 Windows 应用程序中,图形库可以帮助我们生成图像。 类似的技术也可以应用于 Web 应用程序。 在本文中,我们将探讨这些技术。

有时,我们需要创建图表或某种类型的图像,或者可能需要添加水印/版权声明等。

在 HTML 5 出现并支持 canvas 标签之前,此技术可以帮助您为 Web 应用程序动态创建图像。

目标读者

本文的读者预计需要了解 .NET、图形库和 HTTP 处理程序的概念。

基本思路

基本思想非常简单

  1. 使用库创建任何图像。 我们可以从任何流(文件、数据库或其他位置)加载图像。
  2. 将响应类型设置为所需类型的图像(GIF、JPEG、BMP…)。
  3. Response.Write 图像二进制流,从而将此图像推送到客户端。

代码

让我们直接进入代码,因为这里没有什么好说的。

我们首先要做的是初始化 Graphics

Bitmap bitMap = new Bitmap(300, 200); 
Graphics graphics = Graphics.FromImage(bitMap); 

然后我们开始在其中进行一些绘图。 对于此示例,我们将背景设置为金色,并添加一个圆圈、一个正方形、线条和曲线。

SolidBrush solidWhiteBrush = new SolidBrush(Color.Gold); 
graphics.FillRectangle(solidWhiteBrush, 0, 0, 300, 200); 
graphics.FillEllipse(new LinearGradientBrush(new Rectangle(0, 100, 50, 50), 
	Color.Plum, Color.Red, 20), 0, 100, 50, 50); 
graphics.DrawLine(new Pen(Color.Black), 50, 125, 100, 125); 
graphics.FillRectangle(new SolidBrush(Color.Purple), 100, 100, 50, 50); 
graphics.DrawBezier(new Pen(Color.RoyalBlue), 100, 70, 200, 80, 70, 250, 200, 200); 

最后,我们将此图像作为二进制数据写入流。 应该注意的是,内容类型是 image/giv,并且 Save 正在以 GIF 格式保存到流中。

Response.ContentType = "image/gif"; 
bitMap.Save(Response.OutputStream, ImageFormat.Gif); 
Image.png

我如何在实际应用程序中使用它?

在实际应用程序中,此代码应编写在 HTTP 处理程序中,同时图像在 img 标签中显示。

历史

  • 2010 年 7 月 10 日:初始发布
© . All rights reserved.