C#生成缩略图和添加水印类库
C#支持高质量缩略图、文字水印、图片水印、透明度水印源代码类库
using System; using System.Collections; using System.Web; using System.Web.UI; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace DIYSystem.Common.Picture { /**//// <summary> /// 给图片添加水印的 Class。 /// </summary> public class ImageWaterMark { // Fields internal string _sourceimagepath; internal string _watermarkimagepath; internal string _savewatermarkimagepath; internal string _watermarktext; internal ImageAlign _watermarkalign; internal string _thumbnailimagepath; internal int _thumbnailimagewidth; internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.gif|.png|.tif|.tiff|.bmp"; static Hashtable htmimes=new Hashtable(); /**//// <summary> /// 实例化ImageWaterMark /// </summary> public ImageWaterMark(){} static ImageWaterMark() { htmimes[".jpe"]="image/jpeg";#region htmimes[".jpe"]="image/jpeg"; htmimes[".gif"]="image/gif"; htmimes[".jpeg"]="image/jpeg"; htmimes[".jpg"]="image/jpeg"; htmimes[".png"]="image/png"; htmimes[".tif"]="image/tiff"; htmimes[".tiff"]="image/tiff"; htmimes[".bmp"]="image/bmp"; #endregion } Properties#region Properties /**//// <summary> /// 原图片路径和名称(相对路径) /// </summary> public string SourceImagePath { get { return this._sourceimagepath; } set { this._sourceimagepath = value; } } /**//// <summary> /// 生成的缩略图路径(相对路径),如果为空则保存为原图片路径 /// </summary> public string ThumbnailImagePath { get { return (this._thumbnailimagepath); } set { this._thumbnailimagepath = value; } } /**//// <summary> /// 缩略图的宽度(高度与按源图片比例自动生成) /// </summary> public int ThumbnailImageWidth { get { return this._thumbnailimagewidth; } set { this._thumbnailimagewidth = value; } } /**//// <summary> /// 图片水印放置位置 /// </summary> public ImageAlign WaterMarkAlign { get { return (this._watermarkalign); } set { this._watermarkalign = value; } } /**//// <summary> /// 水印图片路径和名称(相对路径) /// </summary> public string WaterMarkImagePath { get { return this._watermarkimagepath; } set { this._watermarkimagepath = value; } } /**//// <summary> /// 保存生成后的水印图片路径和名称(相对路径),如果为空则保存为原图片路径 /// </summary> public string SaveWaterMarkImagePath { get { return this._savewatermarkimagepath; } set { this._savewatermarkimagepath = value; } } /**//// <summary> /// 文字水印 /// </summary> public string WaterMarkText { get { return this._watermarktext; } set { this._watermarktext = value; } } #endregion Methods#region Methods /**//// <summary> /// 获取图像编码解码器的所有相关信息 /// </summary> /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param> /// <returns>返回图像编码解码器的所有相关信息</returns> private static ImageCodecInfo GetCodecInfo(string mimeType) { ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); foreach(ImageCodecInfo ici in CodecInfo) { if(ici.MimeType == mimeType)return ici; } return null; } /**//// <summary> /// 生成缩略图 /// </summary> public void ToThumbnailImage() { if(this.SourceImagePath.ToString()==System.String.Empty) throw new NullReferenceException("SourceImagePath is null!"); string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower(); if(!CheckValidExt(sExt)) { throw new ArgumentException("原图片文件格式不正确,支持的格式有[ "+ AllowExt +" ]","SourceImagePath"); } //从 原图片 创建 Image 对象 Image image = Image.FromFile(HttpContext.Current.Server.MapPath(this.SourceImagePath)); int num = ((this.ThumbnailImageWidth / 4) * 3); int width = image.Width; int height = image.Height; //计算图片的比例 if ((((double) width) / ((double) height)) >= 1.3333333333333333f) { num = ((height * this.ThumbnailImageWidth) / width); } else { this.ThumbnailImageWidth = ((width * num) / height); } if ((this.ThumbnailImageWidth < 1) || (num < 1)) { image.Dispose(); return; } //用指定的大小和格式初始化 Bitmap 类的新实例 Bitmap bitmap = new Bitmap(this.ThumbnailImageWidth, num, PixelFormat.Format32bppArgb); //从指定的 Image 对象创建新 Graphics 对象 Graphics graphics = Graphics.FromImage(bitmap); //清除整个绘图面并以透明背景色填充 graphics.Clear(Color.Transparent); //在指定位置并且按指定大小绘制 原图片 对象 graphics.DrawImage(image, new Rectangle(0, 0, this.ThumbnailImageWidth, num)); image.Dispose(); try { //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 string savepath = (ThumbnailImagePath==null?SourceImagePath:ThumbnailImagePath); SaveImage(bitmap,HttpContext.Current.Server.MapPath(savepath),ImageWaterMark.GetCodecInfo((string)htmimes[sExt])); } catch(System.Exception e) { throw e; } finally { bitmap.Dispose(); graphics.Dispose(); } } /**//// <summary> /// 生成水印图片 /// </summary> /// <returns></returns> public void ToWaterMark() { string savepath = (SaveWaterMarkImagePath==null?SourceImagePath:SaveWaterMarkImagePath); string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower(); if(this.SourceImagePath.ToString()==System.String.Empty) throw new NullReferenceException("SourceImagePath is null!"); if(!CheckValidExt(sExt)) { throw new ArgumentException("原图片文件格式不正确,支持的格式有[ "+ AllowExt +" ]","SourceImagePath"); } //从 原图片 创建 Image 对象 System.IO.FileStream fs = System.IO.File.OpenRead(HttpContext.Current.Server.MapPath(this.SourceImagePath)); Image s_image = Image.FromStream(fs,true); fs.Close(); int s_imagewidth = s_image.Width; int s_imageheight = s_image.Height; float s_imageHorizontalResolution = s_image.HorizontalResolution; float s_imageVerticalResolution = s_image.VerticalResolution; //指定的现有图像并使用指定的大小初始化 Bitmap 类的新实例 Bitmap s_bitmap = new Bitmap(s_image, s_imagewidth, s_imageheight); s_image.Dispose(); //设置此 Bitmap 的分辨率[水平分辨率,垂直分辨率] s_bitmap.SetResolution(72f, 72f); /**/////从指定的 原图片 创建新 Graphics 对象 Graphics s_textgraphics = Graphics.FromImage(s_bitmap); try { if (this.WaterMarkText!=null) { if (this.WaterMarkText.Trim().Length > 0) { //开始制作水印文字 //设置原图片的 对象呈现质量为消除锯齿的呈现 s_textgraphics.SmoothingMode = SmoothingMode.AntiAlias; //在指定位置并且按指定大小绘制 原图片 对象的指定部分[要绘制的 Image 对象,所绘制图像的位置和大小将图像进行缩放以适合该矩形,左上角的 x 坐标,左上角的 y 坐标,绘制的源图像部分的宽度,绘制的源图像部分的高度,将设备像素指定为度量单位] s_textgraphics.DrawImage(s_bitmap, new Rectangle(0, 0, s_imagewidth, s_imageheight), 0, 0, s_imagewidth, s_imageheight, GraphicsUnit.Pixel); // int[] fontsizeArray = new int[7] {16, 14, 12, 10, 8, 6, 4}; //保存水印文字的字体信息 Font wm_textfont = null; //保存在 水印文字 参数中指定的、用 font 参数绘制的字符串的大小(以像素为单位)。 SizeF wm_textsize = new SizeF(0,0); for (int i = 0; i < fontsizeArray.Length; i++) { wm_textfont = new Font("arial", ((float) fontsizeArray[i]), FontStyle.Bold); //测量用 wm_textfont 对象绘制的指定字符串 wm_textsize = s_textgraphics.MeasureString(this.WaterMarkText, wm_textfont); //判断水印文字是否大于 原图片 的宽度 if (((ushort) wm_textsize.Width) < ((ushort) s_imagewidth)) { break; } } fontsizeArray = null; float y = (((float) (s_imageheight - ((int) (((double) s_imageheight) * 0.05f)))) - (wm_textsize.Height / 2f)); float x = ((float) (s_imagewidth / 2)); //设置 水印文字 在布局矩形中居中对齐 StringFormat wm_textformat = new StringFormat(); wm_textformat.Alignment = StringAlignment.Center; //绘制 水印文字 的阴影 s_textgraphics.DrawString(this.WaterMarkText, wm_textfont, new SolidBrush(Color.FromArgb(153, 0, 0, 0)), new PointF((x + 1f), (y + 1f)), wm_textformat); //绘制 水印文字 s_textgraphics.DrawString(this.WaterMarkText, wm_textfont, new SolidBrush(Color.FromArgb(153, 255, 255, 255)), new PointF(x, y), wm_textformat); wm_textformat.Dispose(); } } } catch(System.Exception e) { throw e; } finally { s_textgraphics.Dispose(); } if(this.WaterMarkImagePath==null) { SaveImage(s_bitmap,HttpContext.Current.Server.MapPath(savepath),ImageWaterMark.GetCodecInfo((string)htmimes[sExt])); return; } if(this.WaterMarkImagePath.Trim()==System.String.Empty) { SaveImage(s_bitmap,HttpContext.Current.Server.MapPath(savepath),ImageWaterMark.GetCodecInfo((string)htmimes[sExt])); return; } //从 水印图片 创建 Image 对象 Image wm_image = new Bitmap(HttpContext.Current.Server.MapPath(this.WaterMarkImagePath)); int wm_imagewidth = wm_image.Width;//num3 int wm_imageheight = wm_image.Height;//num4 if (s_imagewidth < wm_imagewidth || s_imageheight < (wm_imageheight * 2)) { SaveImage(s_bitmap,HttpContext.Current.Server.MapPath(this.SourceImagePath),ImageWaterMark.GetCodecInfo((string)htmimes[sExt])); return; } Bitmap s_bitmap2 = new Bitmap(s_bitmap); s_bitmap.Dispose(); //设置分辨率 s_bitmap2.SetResolution(s_imageHorizontalResolution, s_imageVerticalResolution); Graphics wm_imagegraphics = Graphics.FromImage(s_bitmap2); ImageAttributes wm_imageattributes = new ImageAttributes(); /**/////使用颜色重新映射表来调整图像颜色 ColorMap map = new ColorMap(); map.OldColor = Color.FromArgb(255, 0, 255, 0); map.NewColor = Color.FromArgb(0, 0, 0, 0); //为 水印图片 设置颜色重新映射表 wm_imageattributes.SetRemapTable(new ColorMap[]{map}, ColorAdjustType.Bitmap); //为 水印图片 设置颜色调整矩阵 wm_imageattributes.SetColorMatrix(new ColorMatrix(new float[][]{new float[]{1f,0,0,0,0},new float[]{0,1f,0,0,0},new float[]{0,0,1f,0,0},new float[]{0,0,0,0.3f,0},new float[]{0,0,0,0,1f}}), ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int wm_x; int wm_y; // GetWaterMarkXY(out wm_x,out wm_y,s_imagewidth,s_imageheight,wm_imagewidth,wm_imageheight); //在 原图片 上按指定大小绘制 水印图片 对象的指定部分 wm_imagegraphics.DrawImage(wm_image, new Rectangle(wm_x, wm_y, wm_imagewidth, wm_imageheight), 0, 0, wm_imagewidth, wm_imageheight, GraphicsUnit.Pixel, wm_imageattributes); wm_imageattributes.ClearColorMatrix(); wm_imageattributes.ClearRemapTable(); wm_image.Dispose(); wm_imagegraphics.Dispose(); try { //将 绘制水印图片后的图片 以指定格式并用指定的编解码参数保存到指定文件 SaveImage(s_bitmap2,HttpContext.Current.Server.MapPath(savepath),ImageWaterMark.GetCodecInfo((string)htmimes[sExt])); } catch(System.Exception e) { throw e; } finally { s_bitmap2.Dispose(); } } #endregion Helper#region Helper CODE: /**//// <summary> /// 获取水印图片的位置 /// </summary> /// <param name="wm_x">生成水印图片的x值</param> /// <param name="wm_y">生成水印图片的y值</param> /// <param name="s_imagewidth">原图片的宽度</param> /// <param name="s_imageheight">原图片的高度</param> /// <param name="wm_imagewidth">水印图片的宽度</param> /// <param name="wm_imageheight">水印图片的宽度</param> internal void GetWaterMarkXY(out int wm_x,out int wm_y,int s_imagewidth,int s_imageheight,int wm_imagewidth,int wm_imageheight) { if (this.WaterMarkAlign == ImageAlign.LeftTop) { wm_x = 10; wm_y = 10; } else if (this.WaterMarkAlign == ImageAlign.LeftBottom) { wm_x = 10; wm_y = ((s_imageheight - wm_imageheight) - 10); } else if (this.WaterMarkAlign == ImageAlign.RightTop) { wm_x = ((s_imagewidth - wm_imagewidth) - 10); wm_y = 10; } else if (this.WaterMarkAlign == ImageAlign.RightBottom) { wm_x = ((s_imagewidth - wm_imagewidth) - 10); wm_y = ((s_imageheight - wm_imageheight) - 10); } else if (this.WaterMarkAlign == ImageAlign.Center) { wm_x = ((s_imagewidth - wm_imagewidth) / 2); wm_y = ((s_imageheight - wm_imageheight) / 2); } else if (this.WaterMarkAlign == ImageAlign.CenterBottom) { wm_x = ((s_imagewidth - wm_imagewidth) / 2); wm_y = ((s_imageheight - wm_imageheight) - 10); } else if (this.WaterMarkAlign == ImageAlign.CenterTop) { wm_x = ((s_imagewidth - wm_imagewidth) / 2); wm_y = 10; } else { wm_x = ((s_imagewidth - wm_imagewidth) - 10); wm_y = ((s_imageheight - wm_imageheight) - 10); } } /**//// <summary> /// 保存图片 /// </summary> /// <param name="image">Image 对象</param> /// <param name="savePath">保存路径</param> /// <param name="ici">指定格式的编解码参数</param> internal void SaveImage(Image image,string savePath,ImageCodecInfo ici) { //设置 原图片 对象的 EncoderParameters 对象 EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 90)); image.Save(savePath, ici, parameters); parameters.Dispose(); } /**//// <summary> /// 检测扩展名的有效性 /// </summary> /// <param name="sExt">文件名扩展名</param> /// <returns>如果扩展名有效,返回true,否则返回false.</returns> internal bool CheckValidExt(string sExt) { bool flag=false; string[] aExt = AllowExt.Split('|'); foreach(string filetype in aExt) { if(filetype.ToLower()==sExt) { flag = true; break; } } return flag; } #endregion ImageAlign Enumerations#region ImageAlign Enumerations /**//// <summary> /// 指定图像的对齐方式。 /// </summary> public enum ImageAlign:byte { /**//// <summary> /// 图像在左上边缘。 /// </summary> LeftTop, /**//// <summary> /// 图像在左下边缘。 /// </summary> LeftBottom, /**//// <summary> /// 图像在右上边缘。 /// </summary> RightTop, /**//// <summary> /// 图像在右下边缘。 /// </summary> RightBottom, /**//// <summary> /// 图像居中 /// </summary> Center, /**//// <summary> /// 图像在下边缘居中 /// </summary> CenterBottom, /**//// <summary> /// 图像在上边缘居中 /// </summary> CenterTop } #endregion }
加支付宝好友偷能量挖...