[ZT]仿 新华网上的今日头条的标题

有时,我们需要让新闻标题更加个性化,例如:网站首页图片大标题(新闻头条标题等)。如下图:
新华网新闻头条图片

上面这幅图片是新华网上的今日头条的标题。
我们一般的做法可能是:使用Photoshop制作成图片,保存上传。这样需要浪费人力,比较麻烦。有没有更好的办法呢?

下面使用GDI+及C#代码,完成自动实现的过程。

老规矩,先看看运行效果:
在线生成新闻标题

下面是C#代码:
// Text2Image.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Text2Image.aspx.cs" Inherits="BrawDraw.Com.Utility.Utility_Text2Image" %>
<!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">
    </form>
</body>
</html>

// Text2Image.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace BrawDraw.Com.Utility
{
    public partial class Utility_Text2Image : System.Web.UI.Page
    {
        int _width = 480;
        public int Width
        {
            get
            {
                return _width;
            }
            set
            {
                _width = value;
            }
        }

        int _height = 66;
        public int Height
        {
            get
            {
                return _height;
            }
            set
            {
                _height = value;
            }
        }

        string _text = string.Empty;
        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                _text = value;
            }
        }

        string _fontName = "宋体";
        public string FontName
        {
            get
            {
                return _fontName;
            }
            set
            {
                _fontName = value;
            }
        }

        Color _fontColor = Color.Black;
        public Color FontColor
        {
            get
            {
                return _fontColor;
            }
            set
            {
                _fontColor = value;
            }
        }

        Color _backgroundColor = Color.White;
        public Color BackgroundColor
        {
            get
            {
                return _backgroundColor;
            }
            set
            {
                _backgroundColor = value;
            }
        }

        //华文新魏
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["w"] != null)
            {
                try
                {
                    this._width = int.Parse(Request.QueryString["w"].Trim());
                }
                finally
                {
                }
            }

            if (Request.QueryString["h"] != null)
            {
                try
                {
                    this._height = int.Parse(Request.QueryString["h"].Trim());
                }
                finally
                {
                }
            }

            if (Request.QueryString["text"] != null)
            {
                this._text = Request.QueryString["text"].Trim();
            }
            else if (Request.QueryString["t"] != null)
            {
                this._text = Request.QueryString["t"].Trim();
            }

            if (Request.QueryString["font"] != null)
            {
                this._fontName = Request.QueryString["font"].Trim();
            }
            else if (Request.QueryString["f"] != null)
            {
                this._fontName = Request.QueryString["f"].Trim();
            }
            if (this._fontName == "大黑")
            {
                this._fontName = "方正大黑简体";
            }
            string colorString = "Black";
            if (Request.QueryString["color"] != null)
            {
                colorString = Request.QueryString["color"].Trim();
            }
            else if (Request.QueryString["c"] != null)
            {
                colorString = Request.QueryString["c"].Trim();
            }
            if (colorString.StartsWith("_"))
            {
                colorString = "#" + colorString.Remove(0, 1);
            }
            this._fontColor = ConvertColor(colorString);

            string bgColorString = "White";
            if (Request.QueryString["bgcolor"] != null)
            {
                bgColorString = Request.QueryString["bgcolor"].Trim();
            }
            else if (Request.QueryString["b"] != null)
            {
                bgColorString = Request.QueryString["b"].Trim();
            }
            if (bgColorString.StartsWith("_"))
            {
                bgColorString = "#" + bgColorString.Remove(0, 1);
            }

            this._backgroundColor = ConvertColor(bgColorString);

            if (!IsPostBack)
            {
                CreateImage(this.Text, this.Width, this.Height, this.FontName, this.FontColor, this.BackgroundColor);
            }
        }

        //根据验证字符串生成最终图象
        public void CreateImage(string text, int width, int height, string fontName, Color fontColor, Color backgroundColor)
        {
            Bitmap theBitmap = new Bitmap(width, height);
            Graphics theGraphics = Graphics.FromImage(theBitmap);
            theGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            theGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            theGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            //  背景
            theGraphics.Clear(backgroundColor);

            GraphicsPath gp = new GraphicsPath();
            FontFamily fontFamily;
            try
            {
                fontFamily = new FontFamily(fontName);
            }
            catch (Exception exc)
            {
                fontFamily = new FontFamily("宋体");
            }
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Center;

            gp.AddString(text, fontFamily, 0, 60f, new Point(0, 0), format);
            RectangleF rectF = gp.GetBounds();
            float scaleX = width * 1.0f / rectF.Width;
            float scaleY = height * 1.0f / rectF.Height;
            float offsetX = rectF.X * scaleX;
            float offsetY = rectF.Y * scaleY;
            System.Drawing.Drawing2D.Matrix matrix = new Matrix(scaleX, 0, 0, scaleY, -offsetX, -offsetY);
            gp.Transform(matrix);
            Brush newBrush = new SolidBrush(fontColor);
            theGraphics.FillPath(newBrush, gp);
            //theGraphics.DrawRectangle(Pens.Black, 0, 0, width-2, height-2);

            if (gp != null) gp.Dispose();

            //  将生成的图片发回客户端
            MemoryStream ms = new MemoryStream();
            theBitmap.Save(ms, ImageFormat.Png);

            Response.ClearContent(); //需要输出图象信息 要修改HTTP头
            Response.ContentType = "image/Png";
            Response.BinaryWrite(ms.ToArray());
            theGraphics.Dispose();
            theBitmap.Dispose();
            Response.End();
        }

        private Color ConvertColor(string colorString)
        {
            Array knownColors = System.Enum.GetValues(typeof(KnownColor));
            foreach (object colorName in knownColors)
            {
                if (colorString.ToLower() == colorName.ToString().ToLower())
                {
                    return Color.FromName(colorString);
                }
            }

            if (colorString.StartsWith("#"))
            {
                return ColorTranslator.FromHtml(colorString);
            }

            try
            {
                int color32argb = int.Parse(colorString);
                return Color.FromArgb(color32argb);
            }
            finally
            { }

            return Color.Black;
        }
    }
}

调用方法:
<a href="JavaScript:location.href='Text2Image.aspx?text=' + encodeURIComponent('BrawDraw.Com在线生成个性化标题') + '&w=400&h=80&f=' + encodeURIComponent('方正大黑简体') + '&c=_FF0000';">BrawDraw.Com在线生成个性化标题</a>
(其中text后面传入要显示的文字,w或width参数设置图片宽度,h或height设置图片高度,f或font设置字体,c或color设置标题的颜色。)

OK,大功告成。

调用说明:
(1)使用Javascript中encodeURIComponent()方法的目的是对中文字进行编码,以便浏览器能正确接受并被Text2Image.aspx页面接收。
(2)对于类似#FF0000这种颜色形式,由于我们在转入参数中无法直接使用#(“#”在链接中代表锚),所以我这里使用了下划线“_”来代替。color参数除了使用_FF0000这样的颜色之外,你还可以使用类似Red,Blue,Orange,Black等Windows预定义的颜色值(关于预定义颜色值,你可以浏览我之前的BLOG文章“使用GDI+生成KnownColor列表  http://blog.csdn.net/johnsuna/archive/2007/08/27/1761085.aspx”,WPF中取得预定义颜色:http://blog.csdn.net/johnsuna/archive/2008/02/16/2100002.aspx)。如果你对颜色方面感兴趣,你也可以看看这篇:GDI+与WPF中的颜色简析 http://blog.csdn.net/johnsuna/archive/2007/08/27/1761061.aspx
(3)有时,网页可能有背景颜色,那么你还可以加上b或bgcolor参数。由于一般情况是白色背景色,所以,上面的例子就没有这个参数。

(4)如果你是使用静态网页,你可以使用Javascript方式嵌入:
        <Script language="javascript" type="text/javascript">
        document.write('<img src="Text2Image.aspx?text=' + encodeURIComponent('BrawDraw.Com图片处理') + '&w=500&h=80&f=' + encodeURIComponent('华文新魏') + '&c=_FF0000"');
        </Script>

显示效果图:
在线生成个性化新闻标题

或许,你的服务器上没有安装你设置的字体(关于如何取得服务器上已安装字体列表,详见这篇:http://blog.csdn.net/johnsuna/archive/2008/04/14/2290744.aspx),比如下面代码:
<Script language="javascript" type="text/javascript">
        document.write('<img src="Text2Image.aspx?text=' _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" _fcksavedurl=""Text2Image.aspx?text='" + encodeURIComponent('C#中使用GDI+让网站新闻标题个性化') + '&w=500&h=80&f=' + encodeURIComponent('方正大标宋简体') + '&c=_FF0000"');
        </Script>

正常的显示应该是这样:
C#使用GDI+输入新闻标题文字(有该字体时的情况)

如果没有此字体显示出来的效果就是这样:
C#使用GDI+输入新闻标题文字(没有该字体时,显示默认的宋体样式)

原因在于我在下面代码中设置了没有该字体时,则会执行至catch (Exception exc)块内,这里使用了一般带中文操作系统的服务器上都会自动安装的“宋体”字作为默认字体:
            try
            {
                fontFamily = new FontFamily(fontName);
            }
            catch (Exception exc)
            {
                fontFamily = new FontFamily("宋体");
            }

(5)还想在其他网页编程语言(比如:asp, jsp, php等)中调用?如果是,你可以在一台或多台服务器上部署此程序,然后引用即可。只是需要将<img src="Text2Image.aspx?...."中的src属性改成相应服务器的绝对路径。当然,为了更安全或防盗链,你还需要做得更多。本篇不再赘述。

其他:还需要更完善?我想,你可以使用Cache,以提高服务器的效率。或者是,如果你需要生成静态html新闻页面,那么你可以在生成静态页面前自动调用WebService将图片保存下来,然后在静态页面中直接调用此新闻标题图片。



http://blog.csdn.net/johnsuna/archive/2008/04/14/2291627.aspx

原文地址:https://www.cnblogs.com/godwar/p/1163454.html