颐和api

Common.cs 3.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace FileServerApi.Common
  9. {
  10. public class Common
  11. {
  12. /// <summary>
  13. /// 获取文件的MD5码
  14. /// </summary>
  15. /// <param name="fileName">传入的文件名(含路径及后缀名)</param>
  16. /// <returns></returns>
  17. public static string GetMD5HashFromFile(string fileName)
  18. {
  19. try
  20. {
  21. FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
  22. MD5 md5 = new MD5CryptoServiceProvider();
  23. byte[] retVal = md5.ComputeHash(file);
  24. file.Close();
  25. StringBuilder sb = new StringBuilder();
  26. for (int i = 0; i < retVal.Length; i++)
  27. {
  28. sb.Append(retVal[i].ToString("x2"));
  29. }
  30. return sb.ToString();
  31. }
  32. catch (Exception ex)
  33. {
  34. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  35. }
  36. }
  37. /// <summary>
  38. /// 生成缩略图
  39. /// </summary>
  40. /// <param name="path"></param>
  41. /// <param name="fileName"></param>
  42. /// <returns></returns>
  43. public static string GetThumbImg(string path, string fileName,string fileExt)
  44. {
  45. string[] filetypes = new string[] { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
  46. if (filetypes.Contains(fileExt))
  47. {
  48. FileStream file = new FileStream(path + fileName, System.IO.FileMode.Open);
  49. //获取图片的高度和宽度
  50. System.Drawing.Image Img = System.Drawing.Image.FromStream(file);
  51. int _Width = Img.Width;
  52. int _Height = Img.Height;
  53. int _sHeight = 120;//设置生成缩略图的高度
  54. int _sWidth = 120;//设置生成缩略图的宽度
  55. #region 缩略图大小只设置了最大范围,并不是实际大小
  56. float realbili = (float)_Width / (float)_Height;
  57. float wishbili = (float)_sWidth / (float)_sHeight;
  58. //实际图比缩略图最大尺寸更宽矮,以宽为准
  59. if (realbili > wishbili)
  60. {
  61. _sHeight = (int)((float)_sWidth / realbili);
  62. }
  63. //实际图比缩略图最大尺寸更高长,以高为准
  64. else
  65. {
  66. _sWidth = (int)((float)_sHeight * realbili);
  67. }
  68. #endregion
  69. string[] filenames = fileName.Split('.');
  70. string OutThumbFileName = filenames[0].ToString() + "_s." + filenames[1].ToString();
  71. string ImgFilePath = path + OutThumbFileName;
  72. System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
  73. newImg.Save(ImgFilePath);
  74. newImg.Dispose();
  75. Img.Dispose();
  76. return OutThumbFileName;
  77. }
  78. else
  79. {
  80. return "";
  81. }
  82. }
  83. }
  84. }