隨著微軟不斷擴大開放源代碼規模,Codeplex上最熱門的項目就是ASP.NET。
在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);
}
}
運行效果