Пример #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (string.IsNullOrWhiteSpace(txt) || txt.Length > 500) { }
            FontConfig cfg = new FontConfig();

            cfg.text   = txt.Length > 25 ? txt.Substring(0, 25) : txt;
            cfg.size   = Convert.ToInt32(Req("size", cfg.size.ToString()));
            cfg.family = Req("family", cfg.family);
            cfg.color  = Req("color", cfg.color);
            //仅接受16位传参
            cfg.bkcolor = Req("bkcolor", cfg.bkcolor);
            cfg.width   = DataConverter.CLng(Req("width", cfg.width.ToString()));
            if (!cfg.bkcolor.StartsWith("#"))
            {
                cfg.bkcolor = "#" + cfg.bkcolor;
            }
            if (!cfg.color.StartsWith("#"))
            {
                cfg.color = "#" + cfg.color;
            }
            CreateImage(cfg);
        }
Пример #2
0
        private void CreateImage(FontConfig cfg)
        {
            int      margin   = cfg.size / 4;                                                  //每个字之间的间距
            int      mapwidth = (int)(cfg.text.Length * (cfg.size + (cfg.size / 4) + margin)); //必须加大些宽高,否则文字显示不全
            Bitmap   map      = new Bitmap(mapwidth, cfg.size + (cfg.size / 2));               //创建图片背景
            Graphics graph    = Graphics.FromImage(map);

            graph.Clear(colorHx16toRGB(cfg.bkcolor));//清除画面,填充背景
            try
            {
                char[]       chars  = cfg.text.ToCharArray();//拆散字符串成单字符数组
                StringFormat format = new StringFormat(StringFormatFlags.NoClip);
                format.Alignment     = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                //定义字体
                for (int i = 0; i < chars.Length; i++)
                {
                    Font  f = new System.Drawing.Font(cfg.family, cfg.size, System.Drawing.FontStyle.Regular);//字体样式(参数2为字体大小)
                    Brush b = new System.Drawing.SolidBrush(colorHx16toRGB(cfg.color));

                    Point dot = new Point(cfg.size, cfg.size);
                    graph.TranslateTransform(dot.X, dot.Y);   //移动光标到指定位置
                    graph.DrawString(chars[i].ToString(), f, b, 1, -3, format);
                    graph.TranslateTransform(margin, -dot.Y); //移动光标到指定位置,每个字符紧凑显示,避免被软件识别
                }
                //生成图片
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.Cache.SetNoStore();
                Response.ClearContent();
                Response.ContentType = "image/gif";
                Response.BinaryWrite(ms.ToArray());
            }
            catch { }
            finally { graph.Dispose(); map.Dispose(); }
        }