C#图片上传,加水印,自动生成缩略图

简介:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using  System;
using  System.Data;
using  System.Data.SqlClient;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Text;
using  System.Text.RegularExpressions;
using  System.Drawing;
using  System.Drawing.Imaging;
using  System.Collections;
using  System.ComponentModel;
namespace  Legalsoft.Images
{
     /// <summary>
     /// News 的摘要说明
     /// </summary>
     public  class  XImage
     {
         public  Color tBackground;
         public  Color tBorder;
         public  Color tShadow;
         public  int  tQuality;
         public  string  markPosition;
         /// <summary>
         /// 图片参数预定义
         /// </summary>
         static  Hashtable htmimes = new  Hashtable();
         internal  readonly  string  AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif" ;
         public  XImage()
         {
             tBackground = Color.Transparent;
             tBorder = Color.Transparent;
             tShadow = Color.Transparent;
             tQuality = 100;
             markPosition = "左下角" ;
             #region 图片类型预定义
             htmimes[ ".jpe" ]= "image/jpeg" ;
             htmimes[ ".jpeg" ] = "image/jpeg" ;
             htmimes[ ".jpg" ] = "image/jpeg" ;
             htmimes[ ".png" ] = "image/png" ;
             htmimes[ ".tif" ] = "image/tiff" ;
             htmimes[ ".tiff" ] = "image/tiff" ;
             htmimes[ ".bmp" ] = "image/bmp" ;
             htmimes[ ".gif" ] = "image/gif" ;
             #endregion
         }
         #region 下载指定URL图片并保存
         /// <summary>
         /// 下载指定URL的文件并保存到指定目录
         /// </summary>
         /// <param name="strUrl"></param>
         public  void  DownloadImage( string  strUrl, string  file)
         {
             System.Net.WebClient wc = new  System.Net.WebClient();
             wc.DownloadFile(strUrl, file);
         }
         #endregion
         #region C#自动生成缩略图
         /// <summary>
         /// 按给定名字确定颜色
         /// </summary>
         /// <param name="name"></param>
         /// <returns></returns>
         public  Color ToColor( string  name)
         {
             if  (name == "白色" ) return  Color.White;
             if  (name == "红色" ) return  Color.Red;
             if  (name == "蓝色" ) return  Color.Blue;
             if  (name == "绿色" ) return  Color.Green;
             if  (name == "黑色" ) return  Color.Black;
             if  (name == "灰色" ) return  Color.DarkGray;
             if  (name == "黄色" ) return  Color.Yellow;
             if  (name == "紫色" ) return  Color.Cyan;
             if  (name == "无色" ) return  Color.Transparent;
             return  Color.Transparent;
         }
         /// <summary>
         /// 按名字设置各种颜色,可以自行扩充:)
         /// </summary>
         /// <param name="name"></param>
         /// <returns></returns>
         public  int  ToQuality( string  name)
         {
             return  Int32.Parse(name.Replace( "%" , "" ));
         }
         /// <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>
         /// <param name="sExt">文件名扩展名</param>
         /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
         private  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;
         }
         /// <summary>
         /// 保存图片
         /// </summary>
         /// <param name="image">Image 对象</param>
         /// <param name="savePath">保存路径</param>
         /// <param name="ici">指定格式的编解码参数</param>
         private  void  SaveImage(System.Drawing.Image image, string  savePath, ImageCodecInfo ici)
         {
             //设置 原图片 对象的 EncoderParameters 对象
             EncoderParameters parameters = new  EncoderParameters(1);
             parameters.Param[0] = new  EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (( long )tQuality));
             image.Save(savePath, ici, parameters);
             parameters.Dispose();
         }
         /// <summary>
         /// 生成缩略图
         /// </summary>
         /// <param name="sourceImagePath">原图片路径(相对路径)</param>
         /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
         /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>
         public  void  ToThumbnail( string  sourceImagePath, string  thumbnailImagePath, int  thumbnailImageWidth, int  thumbnailImageHeight )
         {
             // 1.先检查图片格式等信息
             string  ThumbnailImagePath = thumbnailImagePath;
             string  SourceImagePath = sourceImagePath;
             string  sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf( "." )).ToLower();
             if  (SourceImagePath.ToString() == System.String.Empty)
             {
                 throw  new  NullReferenceException( "SourceImagePath is null!" );
             }
             if  (!CheckValidExt(sExt))
             {
                 throw  new  ArgumentException( "原图片文件格式不正确,支持的格式有[ "  + AllowExt + " ]" , "SourceImagePath" );
             }
             // 从原图片创建 Image 对象
             System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));
             // 2.计算图片的位置、尺寸等信息
             int  tWidth, tHeight, tLeft, tTop;
             double  fScale = ( double )thumbnailImageHeight / ( double )thumbnailImageWidth; // 高度宽度比
             if  ((( double )image.Width * fScale) > ( double )image.Height) // 如果原图比较宽
             {
                 tWidth = thumbnailImageWidth;
                 tHeight = ( int )(( double )image.Height * ( double )tWidth / ( double )image.Width);
                 tLeft = 0;
                 tTop = (thumbnailImageHeight-tHeight)/2;
             }
             else
             {
                 tHeight = thumbnailImageHeight;
                 tWidth = ( int )(( double )image.Width * ( double )tHeight / ( double )image.Height);
                 tLeft = (thumbnailImageWidth-tWidth)/2;
                 tTop = 0;
             }
             if  (tLeft < 0) tLeft = 0;
             if  (tTop < 0) tTop = 0;
             if  (tBorder != Color.Transparent)
             {
                 tWidth -= 2;
                 tHeight -= 2;
                 tLeft++;
                 tTop++;
             }
             if  (tShadow != Color.Transparent)
             {
                 tWidth -= 1;
                 tHeight -= 1;
             }
             //用指定的大小和格式初始化 Bitmap 类的新实例
             //Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);
             Bitmap bitmap = new  Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);
             //从指定的 Image 对象创建新 Graphics 对象
             Graphics graphics = Graphics.FromImage(bitmap);
             //清除整个绘图面并以透明背景色填充
             if  (tBackground != Color.Transparent)
             {
                 graphics.Clear(tBackground);
             }
             else
             {
                 graphics.Clear(Color.Transparent);
             }
             // 添加阴影
             if  (tShadow != Color.Transparent)
             {
                 Pen shPen = new  Pen(tShadow);
                 graphics.DrawLine(shPen, new  Point(1, thumbnailImageHeight-1), new  Point(thumbnailImageWidth-1, thumbnailImageHeight-1));
                 graphics.DrawLine(shPen, new  Point(thumbnailImageWidth-1, 1), new  Point(thumbnailImageWidth-1, thumbnailImageHeight-1));
             }
             // 添加边框
             if  (tBorder != Color.Transparent)
             {
                 Pen bdPen = new  Pen(tBorder);
                 if  (tShadow != Color.Transparent)
                 {
                     graphics.DrawRectangle(bdPen, new  Rectangle(0, 0, thumbnailImageWidth-2, thumbnailImageHeight-2));
                 }
                 else
                 {
                     graphics.DrawRectangle(bdPen, new  Rectangle(0, 0, thumbnailImageWidth-1, thumbnailImageHeight-1));
                 }
             }
             //在指定位置并且按指定大小绘制 原图片 对象
             graphics.DrawImage(image, new  Rectangle(tLeft, tTop, tWidth, tHeight));
             image.Dispose();
             try
             {
                 //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
                 string  savepath = (ThumbnailImagePath == null  ? SourceImagePath : ThumbnailImagePath);
                 SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo(( string )htmimes[sExt]));
             }
             catch  (System.Exception e)
             {
                 throw  e;
             }
             finally
             {
                 bitmap.Dispose();
                 graphics.Dispose();
             }
         }
         #endregion
         #region C#给图片添加水印
         public  void  Mark( string  sourceImagePath, string  markString)
         {
             // 1.先检查图片格式等信息
             string  markImagePath = sourceImagePath;
             string  SourceImagePath = sourceImagePath;
             string  sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf( "." )).ToLower();
             if  (SourceImagePath.ToString() == System.String.Empty)
             {
                 throw  new  NullReferenceException( "SourceImagePath is null!" );
             }
             if  (!CheckValidExt(sExt))
             {
                 throw  new  ArgumentException( "原图片文件格式不正确,支持的格式有[ "  + AllowExt + " ]" , "SourceImagePath" );
             }
             // 从原图片创建 Image 对象
             System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));
             //用指定的大小和格式初始化 Bitmap 类的新实例
             Bitmap bitmap = new  Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
             //从指定的 Image 对象创建新 Graphics 对象
             Graphics graphics = Graphics.FromImage(bitmap);
             //在指定位置并且按指定大小绘制 原图片 对象
             graphics.DrawImage(image, new  Rectangle(0, 0, image.Width, image.Height));
             #region 绘制水印
             // 设置水印字体
             int  fHeight = image.Height/5;
             if (fHeight>16) fHeight = 16;
             Font drawFont = new  Font( "Arial" , fHeight);
             // 设置水印文字位置,默认为左下角
             float  x = 4;
             float  y = image.Height - drawFont.Height - 4;
             if  (markPosition == "左上角" )
             {
                 y = 4;
             }
             if  (markPosition == "右上角" )
             {
                 x = image.Width - markString.Length * fHeight / 2 - fHeight;
                 y = 4;
             }
             if  (markPosition == "右下角" )
             {
                 x = image.Width - markString.Length * fHeight / 2 - fHeight;
             }
             if  (markPosition == "图片中间" )
             {
                 x = image.Width / 2 - markString.Length * fHeight / 2;
                 y = image.Height / 2 - fHeight / 2;
             }
             StringFormat drawFormat = new  StringFormat();
             drawFormat.FormatFlags = StringFormatFlags.NoWrap;
             // 设置水印文字颜色,先绘制一个黑色字作为阴影,再绘制白色字,这样比较显眼;
             SolidBrush drawBrush = new  SolidBrush(Color.Black);
             graphics.DrawString(markString, drawFont, drawBrush, x, y, drawFormat);
             drawBrush.Color = Color.White;
             graphics.DrawString(markString, drawFont, drawBrush, x-1, y-1, drawFormat);
             #endregion
             image.Dispose();
             try
             {
                 //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
                 string  savepath = SourceImagePath;
                 SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo(( string )htmimes[sExt]));
             }
             catch  (System.Exception e)
             {
                 throw  e;
             }
             finally
             {
                 bitmap.Dispose();
                 graphics.Dispose();
             }
         }
         #endregion
     }
}



    本文转自曾祥展博客园博客,原文链接http://www.cnblogs.com/zengxiangzhan/archive/2009/12/31/1636549.html,如需转载请自行联系原作者


相关文章
|
5月前
|
PHP 数据安全/隐私保护
ueditor上传图片添加水印
博客在上传图片的时候,我希望能打上我博客链接的水印,掘金,csdn都是这么干的,这事我得学习。 平时的图片上传还好说,在文章编辑的时候,使用ueditor上传图片加水印需要修改ueditor部分PHP的源码,我这里大概记录一下。 首先打开php文件夹下的Uploader.class.php
29 0
|
存储 NoSQL 前端开发
一文搞定图片选择及图片上传
本篇介绍了在 Flutter 中如何选择图片文件,图片选择组件的封装和如何将图片上传到后台。通过本篇,可以了解Flutter 构建应用时的图片上传过程。
798 0
|
Java API Maven
一行代码搞定图片缩略图处理
不知道大家现在工作中还有没有使用过Java处理图片的。强哥在大学毕业后,从事服务端WEB开发,就很少接触图片处理。有接触图片的,大多也就是图片的上传下载。所以,对Java处理图片相关的技术也都没怎么接触。
一行代码搞定图片缩略图处理
|
JavaScript
原生js实现图片单张上传及批量上传
原生js实现图片单张上传及批量上传
|
缓存 Java 数据安全/隐私保护
给图片加水印?这是我见过最简单的实现方式
大家好,我是指北君。 在项目中经常有需要在图片上添加水印的需求以及在某些场合下需要身份证图片,这时就可以对身份证上加水印防止被用于其他用途,java 在处理图片水印时不需要额外的第三方包,使用 BufferedImage 和 Graphics2D 就可以搞定
给图片加水印?这是我见过最简单的实现方式
|
前端开发 JavaScript HTML5
使用readAsDataURL方法预览图片
使用FileReader接口的readAsDataURL方法实现图片的预览。  在FileReader出现之前,前端的图片预览是这样实现的:把本地图片上传到服务器,服务器把图片地址返回,并把它替换到图片元素的src属性。
1854 0
|
安全 数据安全/隐私保护
图片上传预览
     最近做需求时遇到的,上传的时候预览一下,一开始并没有想着用插件什么的,太复杂,只是个预览效果,不如自己写省事。前前后后也就几十行代码(包含头尾HTML、注释、输出调试),反正是比引用插件少多了,自己写也是个锻炼。
788 0