图片操作:生成缩略图、添加水印、截取图片等

本文介绍了一个图片处理工具类,该工具类提供了多种图片处理功能,包括生成缩略图、添加水印、截取图片等。支持不同的缩略图生成模式,并能够处理多种图片格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. usingSystem;
  2. usingSystem.Drawing;
  3. usingSystem.Drawing.Imaging;
  4. usingSystem.IO;
  5. usingSystem.Web;
  6. namespaceXXXX.Common
  7. {
  8. ///<summary>
  9. ///图片操作:生成缩略图、添加水印、截取图片等
  10. ///</summary>
  11. publicclassImagesHelper
  12. {
  13. ///<summary>
  14. ///根据文件流获得图片宽度
  15. ///</summary>
  16. ///<paramname="file"></param>
  17. ///<returns></returns>
  18. publicstaticintgetImgWidth(Streamstream)
  19. {
  20. Imageimg=Image.FromStream(stream);
  21. intresult=img.Width;
  22. img.Dispose();
  23. stream.Dispose();
  24. returnresult;
  25. }
  26. ///<summary>
  27. ///根据图片路径获得图片宽度
  28. ///</summary>
  29. ///<paramname="filePath"></param>
  30. ///<returns></returns>
  31. publicstaticintgetImgWidth(stringfilePath)
  32. {
  33. Imageimg=Image.FromFile(filePath);
  34. intresult=img.Width;
  35. img.Dispose();
  36. returnresult;
  37. }
  38. #region从文件流生成缩略图
  39. ///<summary>
  40. ///从文件流生成缩略图
  41. ///</summary>
  42. ///<paramname="stream">数据IO流</param>
  43. ///<paramname="savePath"></param>
  44. ///<paramname="width"></param>
  45. ///<paramname="height"></param>
  46. ///<paramname="scale"></param>
  47. ///<returns></returns>
  48. publicstaticboolGetThumbNail(Streamstream,stringsavePath,intwidth,intheight,ThumbNailScalescale)
  49. {
  50. //缩略图
  51. Imageimg=Image.FromStream(stream);
  52. stream.Dispose();
  53. inttowidth=width;
  54. inttoheight=height;
  55. intx=0;
  56. inty=0;
  57. intow=img.Width;
  58. intoh=img.Height;
  59. //如果图片小于指定宽度
  60. if(ow<width)
  61. width=ow;
  62. if(oh<height)
  63. height=oh;
  64. switch(scale)
  65. {
  66. caseThumbNailScale.Appointed:
  67. break;
  68. caseThumbNailScale.ScaleWidth:
  69. toheight=img.Height*width/img.Width;
  70. break;
  71. caseThumbNailScale.ScaleHeight:
  72. towidth=img.Width*height/img.Height;
  73. break;
  74. caseThumbNailScale.Cut:
  75. if((double)img.Width/(double)img.Height>(double)towidth/(double)toheight)
  76. {
  77. oh=img.Height;
  78. ow=img.Height*towidth/toheight;
  79. y=0;
  80. x=(img.Width-ow)/2;
  81. }
  82. else
  83. {
  84. ow=img.Width;
  85. oh=img.Width*height/towidth;
  86. x=0;
  87. y=(img.Height-oh)/2;
  88. }
  89. break;
  90. caseThumbNailScale.ScaleDown:
  91. doubleTw,Th;
  92. Tw=width;
  93. Th=height*(Convert.ToDouble(oh)/Convert.ToDouble(ow));
  94. if(Th>height)
  95. {
  96. Th=height;
  97. Tw=width*(Convert.ToDouble(ow)/Convert.ToDouble(oh));
  98. }
  99. towidth=Convert.ToInt32(Tw);
  100. toheight=Convert.ToInt32(Th);
  101. break;
  102. default:
  103. break;
  104. }
  105. //新建一个bmp图片
  106. Imagebitmap=newBitmap(towidth,toheight);
  107. //新建一个画板
  108. Graphicsg=Graphics.FromImage(bitmap);
  109. //设置高质量插值法
  110. g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
  111. //设置高质量,低速度呈现平滑程度
  112. g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  113. //清空画布并以透明背景色填充
  114. g.Clear(Color.Transparent);
  115. //在指定位置并且按指定大小绘制原图片的指定部分
  116. g.DrawImage(img,newRectangle(0,0,towidth,toheight),
  117. newRectangle(x,y,ow,oh),
  118. GraphicsUnit.Pixel);
  119. try
  120. {
  121. //以jpg格式保存缩略图
  122. bitmap.Save(savePath,ImageFormat.Jpeg);
  123. }
  124. catch(Exceptionex)
  125. {
  126. Logger.Write(string.Format("从文件流生成缩略图:{0}",ex.Message),Logger.MsgType.Error);
  127. returnfalse;
  128. }
  129. finally
  130. {
  131. img.Dispose();
  132. bitmap.Dispose();
  133. g.Dispose();
  134. }
  135. returntrue;
  136. }
  137. #endregion
  138. #region从文件路径生成缩略图
  139. ///<summary>
  140. ///从图片路径生成缩略图
  141. ///</summary>
  142. ///<paramname="originalImagePath">图片路径</param>
  143. ///<paramname="savePath">保存路径</param>
  144. ///<paramname="width">缩略图宽度</param>
  145. ///<paramname="height">缩略图高度</param>
  146. ///<paramname="mode">HW:指定高宽缩放(可能变形)W://指定宽,高按比例H://指定高,宽按比例Cut://指定高宽裁减(不变形)</param>
  147. ///<returns></returns>
  148. publicstaticboolGetThumbNail(stringoriginalImagePath,stringsavePath,intwidth,intheight,ThumbNailScalescale)
  149. {
  150. //缩略图
  151. Imageimg=Image.FromFile(originalImagePath);
  152. inttowidth=width;
  153. inttoheight=height;
  154. intx=0;
  155. inty=0;
  156. intow=img.Width;
  157. intoh=img.Height;
  158. //如果图片小于指定宽度
  159. if(ow<width)
  160. width=ow;
  161. switch(scale)
  162. {
  163. caseThumbNailScale.Appointed:
  164. break;
  165. caseThumbNailScale.ScaleWidth:
  166. toheight=img.Height*width/img.Width;
  167. break;
  168. caseThumbNailScale.ScaleHeight:
  169. towidth=img.Width*height/img.Height;
  170. break;
  171. caseThumbNailScale.Cut:
  172. if((double)img.Width/(double)img.Height>(double)towidth/(double)toheight)
  173. {
  174. oh=img.Height;
  175. ow=img.Height*towidth/toheight;
  176. y=0;
  177. x=(img.Width-ow)/2;
  178. }
  179. else
  180. {
  181. ow=img.Width;
  182. oh=img.Width*height/towidth;
  183. x=0;
  184. y=(img.Height-oh)/2;
  185. }
  186. break;
  187. caseThumbNailScale.ScaleDown:
  188. doubleTw,Th;
  189. Tw=width;
  190. Th=height*(Convert.ToDouble(oh)/Convert.ToDouble(ow));
  191. if(Th>height)
  192. {
  193. Th=height;
  194. Tw=width*(Convert.ToDouble(ow)/Convert.ToDouble(oh));
  195. }
  196. towidth=Convert.ToInt32(Tw);
  197. toheight=Convert.ToInt32(Th);
  198. break;
  199. default:
  200. break;
  201. }
  202. //新建一个bmp图片
  203. Imagebitmap=newBitmap(towidth,toheight);
  204. //新建一个画板
  205. Graphicsg=Graphics.FromImage(bitmap);
  206. //设置高质量插值法
  207. g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
  208. //设置高质量,低速度呈现平滑程度
  209. g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  210. //清空画布并以透明背景色填充
  211. g.Clear(Color.White);
  212. //在指定位置并且按指定大小绘制原图片的指定部分
  213. g.DrawImage(img,newRectangle(0,0,towidth,toheight),
  214. newRectangle(x,y,ow,oh),
  215. GraphicsUnit.Pixel);
  216. try
  217. {
  218. //以jpg格式保存缩略图
  219. bitmap.Save(savePath,ImageFormat.Jpeg);
  220. }
  221. catch(Exceptione)
  222. {
  223. throwe;
  224. }
  225. finally
  226. {
  227. img.Dispose();
  228. bitmap.Dispose();
  229. g.Dispose();
  230. }
  231. returntrue;
  232. }
  233. #endregion
  234. #region获取图片格式
  235. ///<summary>
  236. ///获取图片格式
  237. ///</summary>
  238. ///<paramname="strContentType"></param>
  239. ///<returns>返回图片格式</returns>
  240. publicstaticImageFormatGetImageType(objectstrContentType)
  241. {
  242. if((strContentType.ToString().ToLower())=="image/pjpeg")
  243. {
  244. returnImageFormat.Jpeg;
  245. }
  246. elseif((strContentType.ToString().ToLower())=="image/gif")
  247. {
  248. returnImageFormat.Gif;
  249. }
  250. elseif((strContentType.ToString().ToLower())=="image/bmp")
  251. {
  252. returnImageFormat.Bmp;
  253. }
  254. elseif((strContentType.ToString().ToLower())=="image/tiff")
  255. {
  256. returnImageFormat.Tiff;
  257. }
  258. elseif((strContentType.ToString().ToLower())=="image/x-icon")
  259. {
  260. returnImageFormat.Icon;
  261. }
  262. elseif((strContentType.ToString().ToLower())=="image/x-png")
  263. {
  264. returnImageFormat.Png;
  265. }
  266. elseif((strContentType.ToString().ToLower())=="image/x-emf")
  267. {
  268. returnImageFormat.Emf;
  269. }
  270. elseif((strContentType.ToString().ToLower())=="image/x-exif")
  271. {
  272. returnImageFormat.Exif;
  273. }
  274. elseif((strContentType.ToString().ToLower())=="image/x-wmf")
  275. {
  276. returnImageFormat.Wmf;
  277. }
  278. else
  279. {
  280. returnImageFormat.MemoryBmp;
  281. }
  282. }
  283. #endregion
  284. ///<summary>
  285. ///生成水印图片
  286. ///</summary>
  287. ///<paramname="sourceFile"></param>
  288. ///<paramname="saveFile">保存文件路径</param>
  289. ///<returns></returns>
  290. publicstaticboolMakeWaterImage(StreamsourceFile,stringsaveFile)
  291. {
  292. boolresult=false;
  293. //水印图片
  294. try
  295. {
  296. ImageimgPhoto=Image.FromStream(sourceFile);
  297. sourceFile.Close();
  298. sourceFile.Dispose();
  299. intphWidth=imgPhoto.Width;
  300. intphHeight=imgPhoto.Height;
  301. BitmapbmPhoto=newBitmap(phWidth,phHeight,PixelFormat.Format24bppRgb);
  302. bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
  303. ImageimgWatermark=newBitmap(System.Web.HttpContext.Current.Server.MapPath("/images/watermark.png"));
  304. intwmWidth=imgWatermark.Width;
  305. intwmHeight=imgWatermark.Height;
  306. if(phWidth>(wmWidth+100)&&phHeight>(wmHeight+100))
  307. {
  308. GraphicsgrPhoto=Graphics.FromImage(bmPhoto);
  309. grPhoto.Clear(Color.White);
  310. grPhoto.DrawImage(imgPhoto,newRectangle(0,0,phWidth,phHeight),0,0,phWidth,phHeight,GraphicsUnit.Pixel);
  311. grPhoto.Dispose();
  312. //添加水印图片
  313. using(BitmapbmWatermark=newBitmap(bmPhoto))
  314. {
  315. bmWatermark.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
  316. GraphicsgrWatermark=Graphics.FromImage(bmWatermark);
  317. using(ImageAttributesimageAttributes=newImageAttributes())
  318. {
  319. //ColorMapcolorMap=newColorMap();
  320. //colorMap.OldColor=Color.FromArgb(255,255,255,255);
  321. //colorMap.NewColor=Color.FromArgb(0,0,0,0);
  322. //ColorMap[]remapTable={colorMap};
  323. //imageAttributes.SetRemapTable(remapTable,ColorAdjustType.Bitmap);
  324. float[][]colorMatrixElements={newfloat[]{1.0f,0.0f,0.0f,0.0f,0.0f},newfloat[]{0.0f,1.0f,0.0f,0.0f,0.0f},newfloat[]{0.0f,0.0f,1.0f,0.0f,0.0f},newfloat[]{0.0f,0.0f,0.0f,1.0f,0.0f},newfloat[]{0.0f,0.0f,0.0f,0.0f,1.0f}};
  325. ColorMatrixwmColorMatrix=newColorMatrix(colorMatrixElements);
  326. imageAttributes.SetColorMatrix(wmColorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);
  327. intxPosOfWm=((phWidth-wmWidth)-2);
  328. intyPosOfWm=((phHeight-wmHeight)-2);
  329. grWatermark.DrawImage(imgWatermark,newRectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight),0,0,wmWidth,wmHeight,GraphicsUnit.Pixel,imageAttributes);
  330. }
  331. imgPhoto=bmWatermark;
  332. grWatermark.Dispose();
  333. imgPhoto.Save(saveFile,ImageFormat.Jpeg);
  334. }
  335. result=true;
  336. }
  337. else
  338. {
  339. result=false;
  340. }
  341. imgWatermark.Dispose();
  342. bmPhoto.Dispose();
  343. imgPhoto.Dispose();
  344. }
  345. catch(Exceptionex)
  346. {
  347. Logger.Write(string.Format("生成水印图片错误:{0}",ex.Message),Logger.MsgType.Information);
  348. try
  349. {
  350. ImageimgPhoto2=Image.FromStream(sourceFile);
  351. imgPhoto2.Save(saveFile,ImageFormat.Jpeg);
  352. imgPhoto2.Dispose();
  353. result=true;
  354. }
  355. catch
  356. {
  357. result=false;
  358. }
  359. }
  360. returnresult;
  361. }
  362. ///<summary>
  363. ///生成水印图片
  364. ///</summary>
  365. ///<paramname="sourceFile"></param>
  366. ///<paramname="saveFile">保存文件路径</param>
  367. ///<paramname="Location">位置0-右下角1-居中2-右上角3-左下角</param>
  368. ///<returns></returns>
  369. publicstaticboolMakeWaterImage(StreamsourceFile,stringsaveFile,ImagePositionPosition)
  370. {
  371. boolresult=false;
  372. //水印图片
  373. try
  374. {
  375. ImageimgPhoto=Image.FromStream(sourceFile);
  376. intphWidth=imgPhoto.Width;
  377. intphHeight=imgPhoto.Height;
  378. BitmapbmPhoto=newBitmap(phWidth,phHeight,PixelFormat.Format24bppRgb);
  379. bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
  380. ImageimgWatermark=newBitmap(System.Web.HttpContext.Current.Server.MapPath("/images/watermark.png"));
  381. intwmWidth=imgWatermark.Width;
  382. intwmHeight=imgWatermark.Height;
  383. if(phWidth>(wmWidth+100)&&phHeight>(wmHeight+100))
  384. {
  385. GraphicsgrPhoto=Graphics.FromImage(bmPhoto);
  386. grPhoto.Clear(Color.White);
  387. grPhoto.DrawImage(imgPhoto,newRectangle(0,0,phWidth,phHeight),0,0,phWidth,phHeight,GraphicsUnit.Pixel);
  388. grPhoto.Dispose();
  389. //添加水印图片
  390. using(BitmapbmWatermark=newBitmap(bmPhoto))
  391. {
  392. bmWatermark.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
  393. GraphicsgrWatermark=Graphics.FromImage(bmWatermark);
  394. using(ImageAttributesimageAttributes=newImageAttributes())
  395. {
  396. //ColorMapcolorMap=newColorMap();
  397. //colorMap.OldColor=Color.FromArgb(255,255,255,255);
  398. //colorMap.NewColor=Color.FromArgb(0,0,0,0);
  399. //ColorMap[]remapTable={colorMap};
  400. //imageAttributes.SetRemapTable(remapTable,ColorAdjustType.Bitmap);
  401. float[][]colorMatrixElements={newfloat[]{1.0f,0.0f,0.0f,0.0f,0.0f},newfloat[]{0.0f,1.0f,0.0f,0.0f,0.0f},newfloat[]{0.0f,0.0f,1.0f,0.0f,0.0f},newfloat[]{0.0f,0.0f,0.0f,1.0f,0.0f},newfloat[]{0.0f,0.0f,0.0f,0.0f,1.0f}};
  402. ColorMatrixwmColorMatrix=newColorMatrix(colorMatrixElements);
  403. imageAttributes.SetColorMatrix(wmColorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);
  404. intxPosOfWm=0;
  405. intyPosOfWm=0;
  406. switch(Position)
  407. {
  408. caseImagePosition.BottomRight:
  409. xPosOfWm=((phWidth-wmWidth)-2);
  410. yPosOfWm=((phHeight-wmHeight)-2);
  411. break;
  412. caseImagePosition.TopLeft:
  413. xPosOfWm=2;
  414. yPosOfWm=2;
  415. break;
  416. caseImagePosition.TopRigth:
  417. xPosOfWm=((phWidth-wmWidth)-2);
  418. yPosOfWm=2;
  419. break;
  420. caseImagePosition.BottomLeft:
  421. xPosOfWm=2;
  422. yPosOfWm=((phHeight-wmHeight)-2);
  423. break;
  424. caseImagePosition.Center:
  425. xPosOfWm=((phWidth/2)-(wmWidth/2));
  426. yPosOfWm=((phHeight/2)-(wmHeight/2));
  427. break;
  428. }
  429. grWatermark.DrawImage(imgWatermark,newRectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight),0,0,wmWidth,wmHeight,GraphicsUnit.Pixel,imageAttributes);
  430. }
  431. imgPhoto=bmWatermark;
  432. grWatermark.Dispose();
  433. imgPhoto.Save(saveFile,ImageFormat.Jpeg);
  434. }
  435. result=true;
  436. }
  437. else
  438. {
  439. ImageimgPhoto2=Image.FromStream(sourceFile);
  440. imgPhoto2.Save(saveFile,ImageFormat.Jpeg);
  441. imgPhoto2.Dispose();
  442. result=true;
  443. }
  444. imgWatermark.Dispose();
  445. bmPhoto.Dispose();
  446. imgPhoto.Dispose();
  447. }
  448. catch
  449. {
  450. try
  451. {
  452. ImageimgPhoto2=Image.FromStream(sourceFile);
  453. imgPhoto2.Save(saveFile,ImageFormat.Jpeg);
  454. imgPhoto2.Dispose();
  455. result=true;
  456. }
  457. catch
  458. {
  459. result=false;
  460. }
  461. }
  462. sourceFile.Close();
  463. sourceFile.Dispose();
  464. returnresult;
  465. }
  466. #region从图片中截取一张指定大小的图片
  467. ///<summary>
  468. ///从图片中截取部分生成新图
  469. ///</summary>
  470. ///<paramname="sFromFilePath">原始图片</param>
  471. ///<paramname="saveFilePath">生成新图</param>
  472. ///<paramname="width">截取图片宽度</param>
  473. ///<paramname="height">截取图片高度</param>
  474. ///<paramname="spaceX">截图图片X坐标</param>
  475. ///<paramname="spaceY">截取图片Y坐标</param>
  476. publicstaticvoidCaptureImage(stringsFromFilePath,stringsaveFilePath,intwidth,intheight,intspaceX,intspaceY)
  477. {
  478. //载入底图
  479. ImagefromImage=Image.FromFile(sFromFilePath);
  480. intx=0;//截取X坐标
  481. inty=0;//截取Y坐标
  482. //原图宽与生成图片宽之差
  483. //当小于0(即原图宽小于要生成的图)时,新图宽度为较小者即原图宽度X坐标则为0
  484. //当大于0(即原图宽大于要生成的图)时,新图宽度为设置值即widthX坐标则为sX与spaceX之间较小者
  485. //Y方向同理
  486. intsX=fromImage.Width-width;
  487. intsY=fromImage.Height-height;
  488. if(sX>0)
  489. {
  490. x=sX>spaceX?spaceX:sX;
  491. }
  492. else
  493. {
  494. width=fromImage.Width;
  495. }
  496. if(sY>0)
  497. {
  498. y=sY>spaceY?spaceY:sY;
  499. }
  500. else
  501. {
  502. height=fromImage.Height;
  503. }
  504. //创建新图位图
  505. Bitmapbitmap=newBitmap(width,height);
  506. //创建作图区域
  507. Graphicsgraphic=Graphics.FromImage(bitmap);
  508. //截取原图相应区域写入作图区
  509. graphic.DrawImage(fromImage,0,0,newRectangle(x,y,width,height),GraphicsUnit.Pixel);
  510. //从作图区生成新图
  511. ImagesaveImage=Image.FromHbitmap(bitmap.GetHbitmap());
  512. //保存图象
  513. saveImage.Save(saveFilePath,ImageFormat.Jpeg);
  514. //释放资源
  515. saveImage.Dispose();
  516. bitmap.Dispose();
  517. graphic.Dispose();
  518. }
  519. #endregion
  520. publicenumImagePosition
  521. {
  522. ///<summary>
  523. ///居中
  524. ///</summary>
  525. Center,
  526. ///<summary>
  527. ///左上角
  528. ///</summary>
  529. TopLeft,
  530. ///<summary>
  531. ///左下角
  532. ///</summary>
  533. BottomLeft,
  534. ///<summary>
  535. ///右下角
  536. ///</summary>
  537. BottomRight,
  538. ///<summary>
  539. ///右上角
  540. ///</summary>
  541. TopRigth
  542. }
  543. ///<summary>
  544. ///图片
  545. ///</summary>
  546. publicenumThumbNailScale
  547. {
  548. ///<summary>
  549. ///指定高宽缩放,图片长宽不一致会变形
  550. ///</summary>
  551. Appointed,
  552. ///<summary>
  553. ///指定宽,高按比例
  554. ///</summary>
  555. ScaleWidth,
  556. ///<summary>
  557. ///指定高,宽按比例
  558. ///</summary>
  559. ScaleHeight,
  560. ///<summary>
  561. ///指定高宽裁减,可能只显示部分图片
  562. ///</summary>
  563. Cut,
  564. ///<summary>
  565. ///按图片比例缩放,不变形,显示全部图片(推荐)
  566. ///</summary>
  567. ScaleDown
  568. }
  569. }
  570. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值