ASP.NET圖片加水印的實(shí)現(xiàn)代碼(C#)
作者:wf5360308(峰)
本文提供了一段ASP.NET圖片加水印的實(shí)現(xiàn)代碼(C#)。代碼實(shí)現(xiàn)的水印為透明文字水印,可以定義文字水印的位置和透明度。
本文介紹ASP.NET圖片加水印的方法。水印為透明文字水印,可以定義文字水印的位置和透明度。
代碼分幾個(gè)部分,請(qǐng)查看代碼中的注釋。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Drawing.Drawing2D;
- namespace DocMIS.AppConfig
- {
- /**//// < summary>
- /// 水印位置
- /// < /summary>
- public enum ImagePosition
- {
- /**//// < summary>
- /// 左上
- /// < /summary>
- LeftTop,
- /**//// < summary>
- /// 左下
- /// < /summary>
- LeftBottom,
- /**//// < summary>
- /// 右上
- /// < /summary>
- RightTop,
- /**//// < summary>
- /// 右下
- /// < /summary>
- RigthBottom,
- /**//// < summary>
- /// 頂部居中
- /// < /summary>
- TopMiddle,
- /**//// < summary>
- /// 底部居中
- /// < /summary>
- BottomMiddle,
- /**//// < summary>
- /// 中心
- /// < /summary>
- Center
- }
- /**//// < summary>
- /// 圖像操作類(主要用于給圖片加上透明文字水印)
- /// < /summary>
- class ImageWater_Word
- {
- private string _ErrMsg;
- #region 出錯(cuò)信息
- /**//// < summary>
- /// 出錯(cuò)信息
- /// < /summary>
- public string ErrMsg
- {
- get { return _ErrMsg; }
- set { _ErrMsg = value; }
- }
- #endregion
- #region 將文件轉(zhuǎn)換成流
- //public byte[] SetImageToByteArray(string fileName, ref string fileSize)
- /**//// < summary>
- /// 將文件轉(zhuǎn)換成流
- /// < /summary>
- /// < param name="fileName">文件全路徑< /param>
- /// < returns>< /returns>
- private byte[] SetImageToByteArray(string fileName)
- {
- byte[] image = null;
- try
- {
- FileStream fs = new FileStream(fileName, FileMode.Open);
- FileInfo fileInfo = new FileInfo(fileName);
- //fileSize = Convert.ToDecimal(fileInfo.Length / 1024).ToString("f2") + " K";
- int streamLength = (int)fs.Length;
- image = new byte[streamLength];
- fs.Read(image, 0, streamLength);
- fs.Close();
- return image;
- }
- catch
- {
- return image;
- }
- }
- #endregion
- #region 將byte轉(zhuǎn)換成MemoryStream類型
- /**//// < summary>
- /// ASP.NET圖片加水?。簩yte轉(zhuǎn)換成MemoryStream類型
- /// < /summary>
- /// < param name="mybyte">byte[]變量< /param>
- /// < returns>< /returns>
- private MemoryStream ByteToStream(byte[] mybyte)
- {
- MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
- return mymemorystream;
- }
- #endregion
- #region 將byte轉(zhuǎn)換成Image文件
- /**//// < summary>
- /// ASP.NET圖片加水?。簩yte轉(zhuǎn)換成Image文件
- /// < /summary>
- /// < param name="mybyte">byte[]變量< /param>
- /// < returns>< /returns>
- private System.Drawing.Image SetByteToImage(byte[] mybyte)
- {
- System.Drawing.Image image;
- MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
- image = System.Drawing.Image.FromStream(mymemorystream);
- return image;
- }
- #endregion
- #region 批量在圖片上添加透明水印文字
- /**//// < summary>
- /// ASP.NET圖片加水印:批量在圖片上添加透明水印文字
- /// < /summary>
- /// < param name="arrsourcePicture">原來圖片地址(路徑+文件名)< /param>
- /// < param name="waterWords">需要添加到圖片上的文字< /param>
- /// < param name="alpha">透明度(0.1~1.0之間)< /param>
- /// < param name="position">文字顯示的位置< /param>
- /// < param name="fRewrite">是否覆蓋原圖片(如果不覆蓋,那么將在同目錄下生成一個(gè)文件名帶0607的文件)< /param>
- /// < returns>< /returns>
- public bool DrawWords(string[] arrsourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
- {
- foreach (string imgPath in arrsourcePicture)
- {
- if (!DrawWords(imgPath, waterWords, alpha, position, fRewrite))
- {
- _ErrMsg += "——處理文件:" + imgPath + " 時(shí)出錯(cuò)。";
- return false;
- }
- }
- return true;
- }
- #endregion
- #region 在圖片上添加透明水印文字
- /**//// < summary>
- /// ASP.NET圖片加水?。涸趫D片上添加透明水印文字
- /// < /summary>
- /// < param name="sourcePicture">原來圖片地址(路徑+文件名)< /param>
- /// < param name="waterWords">需要添加到圖片上的文字< /param>
- /// < param name="alpha">透明度(0.1~1.0之間)< /param>
- /// < param name="position">文字顯示的位置< /param>
- /// < param name="fRewrite">是否覆蓋原圖片(如果不覆蓋,那么將在同目錄下生成一個(gè)文件名帶0607的文件)< /param>
- /// < returns>< /returns>
- public bool DrawWords(string sourcePicture, string waterWords, float alpha, ImagePosition position, bool fRewrite)
- {
- if (!System.IO.File.Exists(sourcePicture))
- {
- _ErrMsg = "文件不存在!";
- return false;
- }
- string fileExtension = System.IO.Path.GetExtension(sourcePicture).ToLower();
- if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
- {
- _ErrMsg = "不是圖片文件!";
- return false;
- }
- Image imgPhoto = null;
- Bitmap bmPhoto = null;
- Graphics grPhoto = null;
- try
- {
- //創(chuàng)建一個(gè)圖片對(duì)象用來裝載要被添加水印的圖片
- imgPhoto = Image.FromStream(ByteToStream(SetImageToByteArray(sourcePicture)));
- //獲取圖片的寬和高
- int phWidth = imgPhoto.Width;
- int phHeight = imgPhoto.Height;
- //建立一個(gè)bitmap,和我們需要加水印的圖片一樣大小
- bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
- //SetResolution:設(shè)置此 Bitmap 的分辨率
- //這里直接將我們需要添加水印的圖片的分辨率賦給了bitmap
- bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
- //Graphics:封裝一個(gè) GDI+ 繪圖圖面。
- grPhoto = Graphics.FromImage(bmPhoto);
- //設(shè)置圖形的品質(zhì)
- grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
- //將我們要添加水印的圖片按照原始大小描繪(復(fù)制)到圖形中
- grPhoto.DrawImage(
- imgPhoto, // 要添加水印的圖片
- new Rectangle(0, 0, phWidth, phHeight), // 根據(jù)要添加的水印圖片的寬和高
- 0, // X方向從0點(diǎn)開始描繪
- 0, // Y方向
- phWidth, // X方向描繪長度
- phHeight, // Y方向描繪長度
- GraphicsUnit.Pixel); // 描繪的單位,這里用的是像素
- //根據(jù)圖片的大小我們來確定添加上去的文字的大小
- //在這里我們定義一個(gè)數(shù)組來確定
- int[] sizes = new int[] { 48, 36, 28, 24, 16, 14, 12, 10 };
- //字體
- Font crFont = null;
- //矩形的寬度和高度,SizeF有三個(gè)屬性,分別為Height高,width寬,IsEmpty是否為空
- SizeF crSize = new SizeF();
- //利用一個(gè)循環(huán)語句來選擇我們要添加文字的型號(hào)
- //直到它的長度比圖片的寬度小
- for (int i = 0; i < sizes.Length; i++)
- {
- crFont = new Font("arial", sizes[i], FontStyle.Bold);
- //測(cè)量用指定的 Font 對(duì)象繪制并用指定的 StringFormat 對(duì)象格式化的指定字符串。
- crSize = grPhoto.MeasureString(waterWords, crFont);
- // ushort 關(guān)鍵字表示一種整數(shù)數(shù)據(jù)類型
- if ((ushort)crSize.Width < (ushort)phWidth)
- break;
- }
- //截邊5%的距離,定義文字顯示(由于不同的圖片顯示的高和寬不同,所以按百分比截取)
- int yPixlesFromBottom = (int)(phHeight * .05);
- //定義在圖片上文字的位置
- float wmHeight = crSize.Height;
- float wmWidth = crSize.Width;
- float xPosOfWm;
- float yPosOfWm;
- //設(shè)置水印的位置
- switch (position)
- {
- case ImagePosition.BottomMiddle:
- xPosOfWm = phWidth / 2;
- yPosOfWm = phHeight - wmHeight - 10;
- break;
- case ImagePosition.Center:
- xPosOfWm = phWidth / 2;
- yPosOfWm = phHeight / 2;
- break;
- case ImagePosition.LeftBottom:
- xPosOfWm = wmWidth;
- yPosOfWm = phHeight - wmHeight - 10;
- break;
- case ImagePosition.LeftTop:
- xPosOfWm = wmWidth / 2;
- yPosOfWm = wmHeight / 2;
- break;
- case ImagePosition.RightTop:
- xPosOfWm = phWidth - wmWidth - 10;
- yPosOfWm = wmHeight;
- break;
- case ImagePosition.RigthBottom:
- xPosOfWm = phWidth - wmWidth - 10;
- yPosOfWm = phHeight - wmHeight - 10;
- break;
- case ImagePosition.TopMiddle:
- xPosOfWm = phWidth / 2;
- yPosOfWm = wmWidth;
- break;
- default:
- xPosOfWm = wmWidth;
- yPosOfWm = phHeight - wmHeight - 10;
- break;
- }
- //封裝文本布局信息(如對(duì)齊、文字方向和 Tab 停靠位),顯示操作(如省略號(hào)插入和國家標(biāo)準(zhǔn) (National) 數(shù)字替換)和 OpenType 功能。
- StringFormat StrFormat = new StringFormat();
- //定義需要印的文字居中對(duì)齊
- StrFormat.Alignment = StringAlignment.Center;
- //SolidBrush:定義單色畫筆。畫筆用于填充圖形形狀,如矩形、橢圓、扇形、多邊形和封閉路徑。
- //這個(gè)畫筆為描繪陰影的畫筆,呈灰色
- int m_alpha = Convert.ToInt32(256 * alpha);
- SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));
- //描繪文字信息,這個(gè)圖層向右和向下偏移一個(gè)像素,表示陰影效果
- //DrawString 在指定矩形并且用指定的 Brush 和 Font 對(duì)象繪制指定的文本字符串。
- grPhoto.DrawString(waterWords, //string of text
- crFont, //font
- semiTransBrush2, //Brush
- new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
- StrFormat);
- //從四個(gè) ARGB 分量(alpha、紅色、綠色和藍(lán)色)值創(chuàng)建 Color 結(jié)構(gòu),這里設(shè)置透明度為153
- //這個(gè)畫筆為描繪正式文字的筆刷,呈白色
- SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
- //第二次繪制這個(gè)圖形,建立在第一次描繪的基礎(chǔ)上
- grPhoto.DrawString(waterWords, //string of text
- crFont, //font
- semiTransBrush, //Brush
- new PointF(xPosOfWm, yPosOfWm), //Position
- StrFormat);
- //imgPhoto是我們建立的用來裝載最終圖形的Image對(duì)象
- //bmPhoto是我們用來制作圖形的容器,為Bitmap對(duì)象
- imgPhoto = bmPhoto;
- //釋放資源,將定義的Graphics實(shí)例grPhoto釋放,grPhoto功德圓滿
- //grPhoto.Dispose();
- //將grPhoto保存
- if (fRewrite)
- {
- imgPhoto.Save(sourcePicture);
- }
- else
- {
- // 目標(biāo)圖片名稱及全路徑
- string targetImage = sourcePicture.Replace(System.IO.Path.GetExtension(sourcePicture), "") + "_0607" + fileExtension;
- imgPhoto.Save(targetImage);
- }
- //imgPhoto.Dispose();
- return true;
- }
- catch (Exception ex)
- {
- _ErrMsg = ex.Message;
- return false;
- }
- finally
- {
- if (imgPhoto != null)
- imgPhoto.Dispose();
- if (bmPhoto != null)
- bmPhoto.Dispose();
- if (grPhoto != null)
- grPhoto.Dispose();
- }
- }
- #endregion
- }
- }
以上就是ASP.NET圖片加水印并處理水印位置和透明度的實(shí)現(xiàn)代碼。
本文來自wf5360308(峰)的博客。
【編輯推薦】
責(zé)任編輯:yangsai
來源:
百度空間