sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

C#图片添加水印操作类
原文链接:https://blog.csdn.net/gongquan2008/article/details/127914150

  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Drawing2D;
  4. using System.Drawing.Imaging;
  5. using System.Web;
  6. using System.IO;
  7. using System.Web.UI;
  8. using System.Xml;
  9. namespace LyUtils
  10. {
  11. #region 水印图片
  12. /// <summary>
  13. /// 水印图片的操作管理
  14. /// </summary>
  15. public class WaterImageManage
  16. {
  17. /// <summary>
  18. /// 添加图片水印
  19. /// </summary>
  20. /// <param name="sourcePicture">源图片文件名</param>
  21. /// <param name="waterImage">水印图片文件名</param>
  22. /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
  23. /// <param name="position">位置</param>
  24. /// <param name="isDeleteSource" >是否删除源</param>
  25. /// <returns>返回生成于指定文件夹下的水印文件名</returns>
  26. public static string DrawImage(string sourcePicture,
  27. string waterImage,
  28. float alpha,
  29. ImagePosition position, bool isDeleteSource
  30. )
  31. {
  32. //
  33. // 判断参数是否有效
  34. //
  35. if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0)
  36. {
  37. return sourcePicture;
  38. }
  39. //
  40. // 源图片,水印图片全路径
  41. //
  42. string sourcePictureName = sourcePicture;
  43. string waterPictureName = waterImage;
  44. string fileSourceExtension = Path.GetExtension(sourcePictureName).ToLower();
  45. string fileWaterExtension = Path.GetExtension(waterPictureName).ToLower();
  46. //
  47. // 判断文件是否存在,以及类型是否正确
  48. //
  49. if (File.Exists(sourcePictureName) == false ||
  50. File.Exists(waterPictureName) == false || (
  51. fileSourceExtension != ".gif" &&
  52. fileSourceExtension != ".jpg" &&
  53. fileSourceExtension != ".png" &&
  54. fileSourceExtension != ".bmp") || (
  55. fileWaterExtension != ".gif" &&
  56. fileWaterExtension != ".jpg" &&
  57. fileWaterExtension != ".png" &&
  58. fileWaterExtension != ".bmp")
  59. )
  60. {
  61. return sourcePicture;
  62. }
  63. //
  64. // 目标图片名称及全路径
  65. //
  66. string targetImage = sourcePictureName.Replace(Path.GetExtension(sourcePictureName), "") + "_1101.jpg";
  67. //
  68. // 将需要加上水印的图片装载到Image对象中
  69. //
  70. Image imgPhoto = Image.FromFile(sourcePictureName);
  71. //
  72. // 确定其长宽
  73. //
  74. int phWidth = imgPhoto.Width;
  75. int phHeight = imgPhoto.Height;
  76. //
  77. // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。
  78. //
  79. Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
  80. //
  81. // 设定分辨率
  82. //
  83. bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
  84. //
  85. // 定义一个绘图画面用来装载位图
  86. //
  87. Graphics grPhoto = Graphics.FromImage(bmPhoto);
  88. //
  89. //同样,由于水印是图片,我们也需要定义一个Image来装载它
  90. //
  91. Image imgWatermark = new Bitmap(waterPictureName);
  92. //
  93. // 获取水印图片的高度和宽度
  94. //
  95. int wmWidth = imgWatermark.Width;
  96. int wmHeight = imgWatermark.Height;
  97. //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
  98. // 成员名称 说明
  99. // AntiAlias 指定消除锯齿的呈现。
  100. // Default 指定不消除锯齿。
  101. // HighQuality 指定高质量、低速度呈现。
  102. // HighSpeed 指定高速度、低质量呈现。
  103. // Invalid 指定一个无效模式。
  104. // None 指定不消除锯齿。
  105. grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
  106. //
  107. // 第一次描绘,将我们的底图描绘在绘图画面上
  108. //
  109. grPhoto.DrawImage(imgPhoto,
  110. new Rectangle(0, 0, phWidth, phHeight),
  111. 0,
  112. 0,
  113. phWidth,
  114. phHeight,
  115. GraphicsUnit.Pixel);
  116. //
  117. // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
  118. //
  119. Bitmap bmWatermark = new Bitmap(bmPhoto);
  120. bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
  121. //
  122. // 继续,将水印图片装载到一个绘图画面grWatermark
  123. //
  124. Graphics grWatermark = Graphics.FromImage(bmWatermark);
  125. //
  126. //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
  127. //
  128. ImageAttributes imageAttributes = new ImageAttributes();
  129. //
  130. //Colormap: 定义转换颜色的映射
  131. //
  132. ColorMap colorMap = new ColorMap();
  133. //
  134. //我的水印图被定义成拥有绿色背景色的图片被替换成透明
  135. //
  136. colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
  137. colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
  138. ColorMap[] remapTable = { colorMap };
  139. imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
  140. float[][] colorMatrixElements = {
  141. new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red红色
  142. new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green绿色
  143. new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue蓝色
  144. new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //透明度
  145. new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//
  146. // ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。
  147. // ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。
  148. ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
  149. imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
  150. ColorAdjustType.Bitmap);
  151. //
  152. //上面设置完颜色,下面开始设置位置
  153. //
  154. int xPosOfWm;
  155. int yPosOfWm;
  156. switch (position)
  157. {
  158. case ImagePosition.BottomMiddle:
  159. xPosOfWm = (phWidth - wmWidth) / 2;
  160. yPosOfWm = phHeight - wmHeight - 10;
  161. break;
  162. case ImagePosition.Center:
  163. xPosOfWm = (phWidth - wmWidth) / 2;
  164. yPosOfWm = (phHeight - wmHeight) / 2;
  165. break;
  166. case ImagePosition.LeftBottom:
  167. xPosOfWm = 10;
  168. yPosOfWm = phHeight - wmHeight - 10;
  169. break;
  170. case ImagePosition.LeftTop:
  171. xPosOfWm = 10;
  172. yPosOfWm = 10;
  173. break;
  174. case ImagePosition.RightTop:
  175. xPosOfWm = phWidth - wmWidth - 10;
  176. yPosOfWm = 10;
  177. break;
  178. case ImagePosition.RigthBottom:
  179. xPosOfWm = phWidth - wmWidth - 10;
  180. yPosOfWm = phHeight - wmHeight - 10;
  181. break;
  182. case ImagePosition.TopMiddle:
  183. xPosOfWm = (phWidth - wmWidth) / 2;
  184. yPosOfWm = 10;
  185. break;
  186. default:
  187. xPosOfWm = 10;
  188. yPosOfWm = phHeight - wmHeight - 10;
  189. break;
  190. }
  191. //
  192. // 第二次绘图,把水印印上去
  193. //
  194. grWatermark.DrawImage(imgWatermark,
  195. new Rectangle(xPosOfWm,
  196. yPosOfWm,
  197. wmWidth,
  198. wmHeight),
  199. 0,
  200. 0,
  201. wmWidth,
  202. wmHeight,
  203. GraphicsUnit.Pixel,
  204. imageAttributes);
  205. imgPhoto.Dispose();
  206. imgPhoto = bmWatermark;
  207. grPhoto.Dispose();
  208. grWatermark.Dispose();
  209. //
  210. // 保存文件到服务器的文件夹里面
  211. //
  212. imgPhoto.Save(targetImage, ImageFormat.Jpeg);
  213. imgPhoto.Dispose();
  214. imgWatermark.Dispose();
  215. if (isDeleteSource)
  216. {
  217. File.Delete(sourcePictureName);
  218. }
  219. targetImage = targetImage.Replace("/", "\\");
  220. return targetImage.Substring(targetImage.LastIndexOf("\\") + 1);
  221. }
  222. /// <summary>
  223. /// 在图片上添加水印文字
  224. /// </summary>
  225. /// <param name="sourcePicture">源图片文件</param>
  226. /// <param name="waterWords">需要添加到图片上的文字</param>
  227. /// <param name="alpha">透明度</param>
  228. /// <param name="position">位置</param>
  229. /// <param name="isDeleteSource">是否删除源</param>
  230. /// <returns></returns>
  231. public static string DrawWords(string sourcePicture,
  232. string waterWords,
  233. float alpha,
  234. ImagePosition position, bool isDeleteSource)
  235. {
  236. //
  237. // 判断参数是否有效
  238. //
  239. if (sourcePicture == string.Empty || waterWords == string.Empty || alpha == 0.0)
  240. {
  241. return sourcePicture;
  242. }
  243. //
  244. // 源图片全路径
  245. //
  246. string sourcePictureName = sourcePicture;
  247. string fileExtension = Path.GetExtension(sourcePictureName).ToLower();
  248. //
  249. // 判断文件是否存在,以及文件名是否正确
  250. //
  251. if (File.Exists(sourcePictureName) == false || (
  252. fileExtension != ".gif" &&
  253. fileExtension != ".jpg" &&
  254. fileExtension != ".png" &&
  255. fileExtension != ".bmp"))
  256. {
  257. return sourcePicture;
  258. }
  259. //
  260. // 目标图片名称及全路径
  261. //
  262. string targetImage = sourcePictureName.Replace(Path.GetExtension(sourcePictureName), "") + "_0703.jpg";
  263. //创建一个图片对象用来装载要被添加水印的图片
  264. Image imgPhoto = Image.FromFile(sourcePictureName);
  265. //获取图片的宽和高
  266. int phWidth = imgPhoto.Width;
  267. int phHeight = imgPhoto.Height;
  268. //
  269. //建立一个bitmap,和我们需要加水印的图片一样大小
  270. Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
  271. //SetResolution:设置此 Bitmap 的分辨率
  272. //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
  273. bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
  274. //Graphics:封装一个 GDI+ 绘图图面。
  275. Graphics grPhoto = Graphics.FromImage(bmPhoto);
  276. //设置图形的品质
  277. grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
  278. //将我们要添加水印的图片按照原始大小描绘(复制)到图形中
  279. grPhoto.DrawImage(
  280. imgPhoto, // 要添加水印的图片
  281. new Rectangle(0, 0, phWidth, phHeight), // 根据要添加的水印图片的宽和高
  282. 0, // X方向从0点开始描绘
  283. 0, // Y方向
  284. phWidth, // X方向描绘长度
  285. phHeight, // Y方向描绘长度
  286. GraphicsUnit.Pixel); // 描绘的单位,这里用的是像素
  287. //根据图片的大小我们来确定添加上去的文字的大小
  288. //在这里我们定义一个数组来确定
  289. int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
  290. //字体
  291. Font crFont = null;
  292. //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空
  293. SizeF crSize = new SizeF();
  294. //利用一个循环语句来选择我们要添加文字的型号
  295. //直到它的长度比图片的宽度小
  296. for (int i = 0; i < 7; i++)
  297. {
  298. crFont = new Font("arial", sizes[i], FontStyle.Bold);
  299. //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。
  300. crSize = grPhoto.MeasureString(waterWords, crFont);
  301. // ushort 关键字表示一种整数数据类型
  302. if ((ushort)crSize.Width < (ushort)phWidth)
  303. break;
  304. }
  305. //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
  306. int yPixlesFromBottom = (int)(phHeight * .05);
  307. //定义在图片上文字的位置
  308. float wmHeight = crSize.Height;
  309. float wmWidth = crSize.Width;
  310. float xPosOfWm;
  311. float yPosOfWm;
  312. switch (position)
  313. {
  314. case ImagePosition.BottomMiddle:
  315. xPosOfWm = phWidth / 2;
  316. yPosOfWm = phHeight - wmHeight - 10;
  317. break;
  318. case ImagePosition.Center:
  319. xPosOfWm = phWidth / 2;
  320. yPosOfWm = phHeight / 2;
  321. break;
  322. case ImagePosition.LeftBottom:
  323. xPosOfWm = wmWidth;
  324. yPosOfWm = phHeight - wmHeight - 10;
  325. break;
  326. case ImagePosition.LeftTop:
  327. xPosOfWm = wmWidth / 2;
  328. yPosOfWm = wmHeight / 2;
  329. break;
  330. case ImagePosition.RightTop:
  331. xPosOfWm = phWidth - wmWidth - 10;
  332. yPosOfWm = wmHeight;
  333. break;
  334. case ImagePosition.RigthBottom:
  335. xPosOfWm = phWidth - wmWidth - 10;
  336. yPosOfWm = phHeight - wmHeight - 10;
  337. break;
  338. case ImagePosition.TopMiddle:
  339. xPosOfWm = phWidth / 2;
  340. yPosOfWm = wmWidth;
  341. break;
  342. default:
  343. xPosOfWm = wmWidth;
  344. yPosOfWm = phHeight - wmHeight - 10;
  345. break;
  346. }
  347. //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。
  348. StringFormat StrFormat = new StringFormat();
  349. //定义需要印的文字居中对齐
  350. StrFormat.Alignment = StringAlignment.Center;
  351. //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
  352. //这个画笔为描绘阴影的画笔,呈灰色
  353. int m_alpha = Convert.ToInt32(256 * alpha);
  354. SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));
  355. //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果
  356. //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。
  357. grPhoto.DrawString(waterWords, //string of text
  358. crFont, //font
  359. semiTransBrush2, //Brush
  360. new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
  361. StrFormat);
  362. //从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153
  363. //这个画笔为描绘正式文字的笔刷,呈白色
  364. SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
  365. //第二次绘制这个图形,建立在第一次描绘的基础上
  366. grPhoto.DrawString(waterWords, //string of text
  367. crFont, //font
  368. semiTransBrush, //Brush
  369. new PointF(xPosOfWm, yPosOfWm), //Position
  370. StrFormat);
  371. //imgPhoto是我们建立的用来装载最终图形的Image对象
  372. //bmPhoto是我们用来制作图形的容器,为Bitmap对象
  373. imgPhoto.Dispose();
  374. imgPhoto = bmPhoto;
  375. //释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满
  376. grPhoto.Dispose();
  377. //将grPhoto保存
  378. imgPhoto.Save(targetImage, ImageFormat.Jpeg);
  379. imgPhoto.Dispose();
  380. if (isDeleteSource)
  381. {
  382. File.Delete(sourcePictureName);
  383. }
  384. targetImage = targetImage.Replace("/", "\\");
  385. return targetImage.Substring(targetImage.LastIndexOf("\\") + 1);
  386. }
  387. /// <summary>
  388. /// 图片位置
  389. /// </summary>
  390. public enum ImagePosition
  391. {
  392. LeftTop, //左上
  393. LeftBottom, //左下
  394. RightTop, //右上
  395. RigthBottom, //右下
  396. TopMiddle, //顶部居中
  397. BottomMiddle, //底部居中
  398. Center //中心
  399. }
  400. }
  401. #endregion
  402. }

posted on 2023-04-11 19:34  sunny123456  阅读(118)  评论(0编辑  收藏  举报