ImageHelper.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Configuration;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Web;
  6. using Utils.ImageUtils;
  7. namespace SiteCore
  8. {
  9. public class ImageHelper
  10. {
  11. public static string UserPicPath = ConfigurationManager.AppSettings["UserPicPath"];
  12. public static int oneFileSize = 5 * 1024 * 1024;
  13. public static string fileFilter = "jpg,jpeg,bmp,png,gif";
  14. private const string pubExt = ".jpg";
  15. private const string marker = "csbq.cn";
  16. //检查目录并创建
  17. public static void directoryChkMD(string sPath)
  18. {
  19. if (!Directory.Exists(sPath))
  20. {
  21. Directory.CreateDirectory(sPath);
  22. }
  23. }
  24. /// <summary>
  25. /// 检测图片是否符合
  26. /// </summary>
  27. /// <param name="postedFile"></param>
  28. /// <param name="errMsg"></param>
  29. /// <returns></returns>
  30. public static bool CheckImage(HttpPostedFile postedFile, out string errMsg)
  31. {
  32. errMsg = "";
  33. if (postedFile == null || postedFile.FileName == "")
  34. {
  35. errMsg = "请选择要上传的图片";
  36. return false;
  37. }
  38. if (postedFile.ContentLength > oneFileSize)
  39. {
  40. errMsg = "上传的图片大小不允许超过5MB";
  41. return false;
  42. }
  43. string sourceExt = Path.GetExtension(postedFile.FileName);
  44. sourceExt = sourceExt.TrimStart('.');
  45. //属于这类扩展名
  46. if (fileFilter.IndexOf(sourceExt, StringComparison.OrdinalIgnoreCase) == -1)
  47. {
  48. errMsg = "请上传扩展名为:" + fileFilter + "的图片";
  49. return false;
  50. }
  51. return true;
  52. }
  53. /// <summary>
  54. /// 上传用户图片
  55. /// </summary>
  56. /// <param name="postedFile"></param>
  57. /// <param name="uCode"></param>
  58. /// <param name="errMsg"></param>
  59. /// <returns></returns>
  60. public static string UpLoadUserPic(HttpPostedFile postedFile, string uCode, out string errMsg)
  61. {
  62. //检测成功
  63. if (CheckImage(postedFile, out errMsg))
  64. {
  65. try
  66. {
  67. using (Image im = Image.FromStream(postedFile.InputStream))
  68. {
  69. //if (im.Width > 800 && im.Height > 700)
  70. //{
  71. // errMsg = "上传图片的宽度和高度不能超过800(宽)*700(高)";
  72. // return "";
  73. //}
  74. //自定义图片名
  75. string fileName = uCode;
  76. string _imgPath = UserPicPath;
  77. directoryChkMD(_imgPath);
  78. string _imgFile = Path.Combine(_imgPath, fileName + pubExt);
  79. ImageMaker.ToThumbnailImages(im, _imgFile, 120, 110);
  80. return fileName + pubExt;
  81. }
  82. }
  83. catch
  84. {
  85. errMsg = "对不起,上传照片发生错误!";
  86. }
  87. }
  88. return "";
  89. }
  90. }
  91. }