FileUpload.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.IO;
  5. using IwbZero.ToolCommon.LogHelpers;
  6. namespace IwbZero.ToolCommon.FileHelpers
  7. {
  8. public static class FileUpload
  9. {
  10. private static string GetFileExt(string fileName)
  11. {
  12. string fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1, fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1);
  13. return fileExt.ToLower();
  14. }
  15. public static string Base64ToFile(this string base64Str, string fileName, string filePath, string fileExt)
  16. {
  17. fileName = $"{fileName}.{fileExt}";
  18. string lcRetVal = Base64ToFile(base64Str, fileName, filePath);
  19. return lcRetVal;
  20. }
  21. public static string Base64ToFile(this string base64Str, string fileName, string filePath)
  22. {
  23. string lcRetVal = "error@";
  24. try
  25. {
  26. filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath);
  27. filePath = filePath.EndsWith("/") ? filePath : (filePath + "/");
  28. string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
  29. if (!Directory.Exists(path))
  30. Directory.CreateDirectory(path);
  31. byte[] bytes = Convert.FromBase64String(base64Str);
  32. using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create, FileAccess.Write))
  33. {
  34. fs.Write(bytes, 0, bytes.Length);
  35. fs.Close();
  36. }
  37. lcRetVal = filePath + fileName;
  38. }
  39. catch (Exception e)
  40. {
  41. typeof(FileUpload).LogError(e);
  42. lcRetVal += "文件上传异常。";
  43. }
  44. return lcRetVal;
  45. }
  46. public static string Base64ToPng(this string base64Str, string fileName, string filePath = "/Image")
  47. {
  48. string lcRetVal = "error@";
  49. try
  50. {
  51. fileName = $"{fileName}-{DateTime.Now:yyMMddHHmmss}{new Random().Next(1000, 9999)}.png";
  52. filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath);
  53. filePath = filePath.EndsWith("/") ? filePath : (filePath + "/");
  54. string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
  55. if (!Directory.Exists(path))
  56. Directory.CreateDirectory(path);
  57. byte[] bytes = Convert.FromBase64String(base64Str);
  58. using (MemoryStream ms = new MemoryStream(bytes))
  59. {
  60. var img = Image.FromStream(ms);
  61. img.Save($"{path}{fileName}");
  62. }
  63. lcRetVal = filePath + fileName;
  64. }
  65. catch (Exception e)
  66. {
  67. typeof(FileUpload).LogError(e);
  68. lcRetVal += "文件上传异常。";
  69. }
  70. return lcRetVal;
  71. }
  72. public static void DeleteFile(this string filePath)
  73. {
  74. try
  75. {
  76. filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath);
  77. string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
  78. if (File.Exists(path))
  79. File.Delete(path);
  80. }
  81. catch
  82. {
  83. //
  84. }
  85. }
  86. /// <summary>
  87. /// 无损压缩图片
  88. /// </summary>
  89. /// <param name="sFile">原图片地址</param>
  90. /// <param name="dFile">压缩后保存图片地址</param>
  91. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  92. /// <param name="size">压缩后图片的最大大小</param>
  93. /// <param name="sfsc">是否是第一次调用</param>
  94. /// <returns></returns>
  95. public static bool CompressImage(this string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
  96. {
  97. //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  98. FileInfo firstFileInfo = new FileInfo(sFile);
  99. if (sfsc && firstFileInfo.Length < size * 1024)
  100. {
  101. if (File.Exists(dFile))
  102. {
  103. File.Delete(dFile);
  104. }
  105. firstFileInfo.CopyTo(dFile);
  106. return true;
  107. }
  108. Image iSource = Image.FromFile(sFile);
  109. ImageFormat tFormat = iSource.RawFormat;
  110. int dHeight = iSource.Height / 2;
  111. int dWidth = iSource.Width / 2;
  112. int sW, sH;
  113. //按比例缩放
  114. Size temSize = new Size(iSource.Width, iSource.Height);
  115. if (temSize.Width > dHeight || temSize.Width > dWidth)
  116. {
  117. if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
  118. {
  119. sW = dWidth;
  120. sH = (dWidth * temSize.Height) / temSize.Width;
  121. }
  122. else
  123. {
  124. sH = dHeight;
  125. sW = (temSize.Width * dHeight) / temSize.Height;
  126. }
  127. }
  128. else
  129. {
  130. sW = temSize.Width;
  131. sH = temSize.Height;
  132. }
  133. //新建第二个bitmap类型的bmp2变量,我这里是根据我的程序需要设置的。
  134. Bitmap ob = new Bitmap(dWidth, dHeight, PixelFormat.Format16bppRgb555);
  135. Graphics g = Graphics.FromImage(ob);
  136. //Bitmap ob = new Bitmap(dWidth, dHeight);
  137. //Graphics g = Graphics.FromImage(ob);
  138. g.Clear(Color.WhiteSmoke);
  139. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  140. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  141. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  142. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  143. g.Dispose();
  144. //将第一个bmp拷贝到bmp2中
  145. //Bitmap ob = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format16bppRgb555);
  146. //Graphics draw = Graphics.FromImage(ob);
  147. //draw.DrawImage(bmp, 0, 0);
  148. //draw.Dispose();
  149. //以下代码为保存图片时,设置压缩质量
  150. EncoderParameters ep = new EncoderParameters();
  151. long[] qy = new long[1];
  152. qy[0] = flag;//设置压缩的比例1-100
  153. EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
  154. ep.Param[0] = eParam;
  155. try
  156. {
  157. ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
  158. ImageCodecInfo jpegIcIinfo = null;
  159. var ext = GetFileExt(dFile)?.ToUpper();
  160. foreach (var t in arrayIci)
  161. {
  162. if (t.FormatDescription.Equals(ext))
  163. {
  164. jpegIcIinfo = t;
  165. break;
  166. }
  167. }
  168. if (jpegIcIinfo != null)
  169. {
  170. ob.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
  171. FileInfo fi = new FileInfo(dFile);
  172. if (fi.Length > 1024 * size)
  173. {
  174. flag = flag - 10;
  175. CompressImage(sFile, dFile, flag, size, false);
  176. }
  177. }
  178. else
  179. {
  180. ob.Save(dFile, tFormat);
  181. }
  182. return true;
  183. }
  184. catch (Exception e)
  185. {
  186. typeof(FileUpload).LogError(e);
  187. return false;
  188. }
  189. finally
  190. {
  191. iSource.Dispose();
  192. //bmp.Dispose();
  193. ob.Dispose();
  194. }
  195. }
  196. /// <summary>
  197. /// 无损压缩图片
  198. /// </summary>
  199. /// <param name="fileStream">原图片</param>
  200. /// <param name="dFile">压缩后保存图片地址</param>
  201. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  202. /// <param name="size">压缩后图片的最大大小</param>
  203. /// <param name="sfsc">是否是第一次调用</param>
  204. /// <returns></returns>
  205. public static bool CompressImage(this MemoryStream fileStream, string dFile, int flag = 90, int size = 300, bool sfsc = true)
  206. {
  207. //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  208. Image iSource = Image.FromStream(fileStream);
  209. if (sfsc && fileStream.Length < size * 1024)
  210. {
  211. iSource.Save(dFile);
  212. return true;
  213. }
  214. ImageFormat tFormat = iSource.RawFormat;
  215. int dHeight = iSource.Height / 2;
  216. int dWidth = iSource.Width / 2;
  217. int sW, sH;
  218. //按比例缩放
  219. Size temSize = new Size(iSource.Width, iSource.Height);
  220. if (temSize.Width > dHeight || temSize.Width > dWidth)
  221. {
  222. if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
  223. {
  224. sW = dWidth;
  225. sH = (dWidth * temSize.Height) / temSize.Width;
  226. }
  227. else
  228. {
  229. sH = dHeight;
  230. sW = (temSize.Width * dHeight) / temSize.Height;
  231. }
  232. }
  233. else
  234. {
  235. sW = temSize.Width;
  236. sH = temSize.Height;
  237. }
  238. Bitmap ob = new Bitmap(dWidth, dHeight);
  239. Graphics g = Graphics.FromImage(ob);
  240. g.Clear(Color.WhiteSmoke);
  241. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  242. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  243. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  244. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  245. g.Dispose();
  246. //以下代码为保存图片时,设置压缩质量
  247. EncoderParameters ep = new EncoderParameters();
  248. long[] qy = new long[1];
  249. qy[0] = flag;//设置压缩的比例1-100
  250. EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
  251. ep.Param[0] = eParam;
  252. try
  253. {
  254. ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
  255. ImageCodecInfo jpegIcIinfo = null;
  256. foreach (var t in arrayIci)
  257. {
  258. if (t.FormatDescription.Equals("JPEG"))
  259. {
  260. jpegIcIinfo = t;
  261. break;
  262. }
  263. }
  264. if (jpegIcIinfo != null)
  265. {
  266. ob.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
  267. FileInfo fi = new FileInfo(dFile);
  268. if (fi.Length > 1024 * size)
  269. {
  270. flag = flag - 10;
  271. CompressImage(fileStream, dFile, flag, size, false);
  272. }
  273. }
  274. else
  275. {
  276. ob.Save(dFile, tFormat);
  277. }
  278. return true;
  279. }
  280. catch
  281. {
  282. return false;
  283. }
  284. finally
  285. {
  286. iSource.Dispose();
  287. ob.Dispose();
  288. }
  289. }
  290. }
  291. }