日期:2014-05-17 浏览次数:20668 次
public partial class CheckImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string randomStr = Session["randomStr"].ToString();
        CreateImage(randomStr);
    }
    //随机颜色
    private Color randomColor()
    {
        Random rd = new Random();
        int red = rd.Next(0, 256);
        int green = rd.Next(0, 256);
        int blue = rd.Next(0, 256);
        return Color.FromArgb(red, green, blue);
    }
    //随机字体
    private string randomFontType()
    {
        Random rd = new Random();
        string[] fonts = new string[] { "Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black", "Quantzite" };
        int length = fonts.Length;
        return fonts[rd.Next(0, length)];
    }
    //随机字体大小
    private int randomFontSize()
    {
        Random rd = new Random();
        int i = rd.Next(15, 25);
        return i;
    }
    //随机字体样式
    private FontStyle randomFontStyle()
    {
        Random rd = new Random();
        FontStyle[] fontStyles = new FontStyle[] { FontStyle.Bold, FontStyle.Italic, FontStyle.Regular, FontStyle.Strikeout, FontStyle.Underline };
        int length = fontStyles.Length;
        return fontStyles[rd.Next(0, length)];
    }
    private void CreateImage(string randomString)
    {
        Bitmap image = new Bitmap(150, 50);
        Graphics g = Graphics.FromImage(image);
        g.Clear(Color.White);
        int i = 5;
        foreach (char c in randomString)
        {
            Font f = new Font(randomFontType(), randomFontSize(), randomFontStyle());
            Brush b = new SolidBrush(randomColor());
            g.DrawString(c.ToString(), f, b, i, 10);
            i += 25;
        }
        //g.DrawString(randomString[0].ToString(), f, brush, 5, 10);
        MemoryStream ms = new MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "image/jpeg";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
}