using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace FileServerApi.Common { public class Common { /// /// 获取文件的MD5码 /// /// 传入的文件名(含路径及后缀名) /// public static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, System.IO.FileMode.Open); MD5 md5 = new MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } } /// /// 生成缩略图 /// /// /// /// public static string GetThumbImg(string path, string fileName,string fileExt) { string[] filetypes = new string[] { ".jpg", ".jpeg", ".gif", ".bmp", ".png" }; if (filetypes.Contains(fileExt)) { FileStream file = new FileStream(path + fileName, System.IO.FileMode.Open); //获取图片的高度和宽度 System.Drawing.Image Img = System.Drawing.Image.FromStream(file); int _Width = Img.Width; int _Height = Img.Height; int _sHeight = 120;//设置生成缩略图的高度 int _sWidth = 120;//设置生成缩略图的宽度 #region 缩略图大小只设置了最大范围,并不是实际大小 float realbili = (float)_Width / (float)_Height; float wishbili = (float)_sWidth / (float)_sHeight; //实际图比缩略图最大尺寸更宽矮,以宽为准 if (realbili > wishbili) { _sHeight = (int)((float)_sWidth / realbili); } //实际图比缩略图最大尺寸更高长,以高为准 else { _sWidth = (int)((float)_sHeight * realbili); } #endregion string[] filenames = fileName.Split('.'); string OutThumbFileName = filenames[0].ToString() + "_s." + filenames[1].ToString(); string ImgFilePath = path + OutThumbFileName; System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero); newImg.Save(ImgFilePath); newImg.Dispose(); Img.Dispose(); return OutThumbFileName; } else { return ""; } } } }