狂野都城

一壶浊酒喜相逢,古今多少事, 都付笑谈中。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用.Net生成图片

Posted on 2005-12-21 13:18  狂野都城  阅读(862)  评论(0)    收藏  举报

经常会看到一些站点在验证的时候随机生成图片,使用.Net提供的类库来实现是非常简单的事,只有区区几行代码.


//--------------------以下是 C#.net 代码--------------------

using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace Benny
{
    public class test : System.Web.UI.Page
    {
        private void Page_Load(object sender, System.EventArgs e)
        {
            this.Response.Clear();
            this.Response.ContentType = "image/jpeg";
            Bitmap bmp = new Bitmap(60, 20);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.Black);
            g.DrawString("1234", new Font("黑体", 12, FontStyle.Regular), new SolidBrush(Color.White), new PointF(2,4));
            bmp.Save(this.Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
            this.Response.End();
        }

        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        private void InitializeComponent()
        {    
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
    }
}

 

这里只是生成一个宽度为60px,高度为20px,背景色为黑色,文字为白色,内容为1234的jpg图片
画完之后输出就OK,呵呵..太简单了