在ASP.NET WebForms下有個ASP.NET Image Generation子項目,為ASP.Net項目裡處理圖片帶來了便利。
項目簡介:ASP.NET Image Generation is a speedy way of generating, transforming, caching images in ASP.Net
下載:http://aspnet.codeplex.com/Wiki/VIEw.ASPx?title=Image%20Generation&referringTitle=Home
.Net Framework:3.5
代碼示例:
Default.ASPx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.ASPx.cs" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Web.GeneratedImage" Namespace="Microsoft.Web" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xHtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:GeneratedImage ID="GeneratedImage1"
runat="server" ImageHandlerUrl="~/TextImageHandler.ashx" >
<Parameters>
<cc1:ImageParameter Name="Hello" Value="text in an image" />
</Parameters>
</cc1:GeneratedImage>
</div>
</form>
</body>
</Html>
TextImageHandler.ashx
<%@ WebHandler Language="C#" Class="TextImageHandler" %>
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Web;
using Microsoft.Web;
public class TextImageHandler : ImageHandler {
public TextImageHandler() {
this.ContentType = System.Drawing.Imaging.ImageFormat.Png;
}
public override ImageInfo GenerateImage(NameValueCollection parameters) {
// Add image generation logic here and return an instance of ImageInfo
Bitmap bit = new Bitmap(300, 60);
Graphics gra = Graphics.FromImage(bit);
gra.Clear(Color.AliceBlue);
gra.DrawString(parameters["Hello"], new Font(FontFamily.GenericSansSerif, 16), Brushes.Black, 0, 0);
return new ImageInfo(bit);
}
}
運行效果