程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> C# 添加文字水印類代碼

C# 添加文字水印類代碼

編輯:ASP.NET基礎
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
namespace Chen
{
public class warterfont
{
public void addtexttoimg(string filename, string text)
{
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(filename)))
{
throw new FileNotFoundException("the file don't exist!");
}
if (text == string.Empty)
{
return;
}
//還需要判斷文件類型是否為圖像類型,這裡就不贅述了
Image image = Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(filename));
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); //輸出處理後的圖像,這裡為了演示方便,我將圖片顯示在頁面中了
bitmap.Save(System.Web.HttpContext.Current.Server.MapPath("/" + "aa.jpg"), ImageFormat.Jpeg); //保存到磁盤上
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved