经常看见朋友拥有非常有个性的签名,真是让我羡慕不 已。虽然有专门的软件可以把图片文件转换成由字符组成的 签名,但是注册费大多非常昂贵,太不划算了。现在有了. NET,其System.Drawing类库的功能非常健全,我们再也 不用去找各种API来做琐碎的准备工作了,所以我们自己写 一个这样的软件便十分简单了。今天就让我们用C#来做一 个从图片到HTML文字图的转换类,让我们也拥有自己的 个性签名。
首先让我们来看看程序的实现原理。其实原理超级简 单,我们只需要通过Bitmap把图片读入,然后通过GetPixel 方法,将图片的颜色取出来,然后转换为 HTML 支持的 HexColor ,将颜色应用于文字,这样就实现了彩色的 HTML文字图。
好了,下面我们动手实现这个类。先在VS.NET中新建 一个C#的类库,然后在引用中添加System.Drawing类库。 下面开始编写代码:
using System;
using System.Drawing;
using System.Text;
namespace Blood.Com.ClassLib
{
/// <summary>
/// 将图片转换为Html
/// </summary>
public class Picture2HtmlPicture
{
/// <summary>
/// 构造函数
/// </summary>
public Picture2HtmlPicture()
{
// 构造函数
}
/// <summary>
/// 将图片转换为HTML
/// </summary>
/// <param name="FileName">图片文件名</param>
/// <returns>HTML内容</returns>
public string MakeHtmlPicture(string FileName)
{
try
{
int intX;
int intY;
int intWidth;
Color clrPicture;
Bitmap bmpPicture;
StringBuilder sb = new StringBuilder();
// 检测文件名是否为空,如果为空,则返回空
if (FileName == "")
{
return null;
}
// 打开图片文件
bmpPicture = new Bitmap(FileName);
sb.Append("<Html>\r\n");
sb.Append("<Body>\r\n");
sb.Append("<style>\r\n");
sb.Append(".Font{font-family: Arial; font-size: 1px}\r\n");
sb.Append("</style>\r\n");
intWidth = bmpPicture.Size.Width;
if (intWidth < 100)
{
intWidth = 100;
}
else
{
intWidth = bmpPicture.Size.Width + 50;
}
sb.Append("<Font Class=\"Font\">\r\n");
// 通过循环,将图片的颜色提取出来