本文要提供的類可以為圖片加文字水印,以及判斷是否是圖片文件。經過測試可運行,例子請下載:http://hovertree.com/h/bjaf/5qc5eh6y.htm
例子效果圖:
以下是HovercWarter類的代碼:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace HoverTreeBatch.HovercFrame
{
public class HovercWarter
{
public static Image AddTextToImg(Image image, string text)
{
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 12.0f; //字體大小
float textWidth = text.Length * fontSize; //文本的長度
//下面定義一個矩形區域,以後在這個矩形裡畫上白底黑字
float rectX = 0;
float rectY = 0;
float rectWidth = text.Length * (fontSize + 8);
float rectHeight = fontSize + 8;
//聲明矩形域
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
Font font = new Font("宋體", fontSize); //定義字體
Brush whiteBrush = new SolidBrush(Color.White); //白筆刷,畫文字用
Brush blackBrush = new SolidBrush(Color.Black); //黑筆刷,畫背景用
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
g.DrawString(text, font, whiteBrush, textArea);
MemoryStream ms = new MemoryStream();
//保存為Jpg類型
bitmap.Save(ms, ImageFormat.Jpeg);
Image h_hovercImg = Image.FromStream(ms);
g.Dispose();
bitmap.Dispose();
return h_hovercImg;
}
/// <summary>
/// 根據文件頭判斷上傳的文件類型
/// </summary>
/// <param name="filePath">filePath是文件的完整路徑 </param>
/// <returns>返回true或false</returns>
public static bool IsPicture(string filePath)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
buffer = reader.ReadByte();
fileClass = buffer.ToString();
buffer = reader.ReadByte();
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")
//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}
}