C# 添加文字浮水印類代碼

來源:互聯網
上載者:User

複製代碼 代碼如下: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();
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.