using System; using System.Configuration; using System.Drawing; using System.IO; using System.Web; using Utils.ImageUtils; namespace SiteCore { public class ImageHelper { public static string UserPicPath = ConfigurationManager.AppSettings["UserPicPath"]; public static int oneFileSize = 5 * 1024 * 1024; public static string fileFilter = "jpg,jpeg,bmp,png,gif"; private const string pubExt = ".jpg"; private const string marker = "csbq.cn"; //检查目录并创建 public static void directoryChkMD(string sPath) { if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } } /// /// 检测图片是否符合 /// /// /// /// public static bool CheckImage(HttpPostedFile postedFile, out string errMsg) { errMsg = ""; if (postedFile == null || postedFile.FileName == "") { errMsg = "请选择要上传的图片"; return false; } if (postedFile.ContentLength > oneFileSize) { errMsg = "上传的图片大小不允许超过5MB"; return false; } string sourceExt = Path.GetExtension(postedFile.FileName); sourceExt = sourceExt.TrimStart('.'); //属于这类扩展名 if (fileFilter.IndexOf(sourceExt, StringComparison.OrdinalIgnoreCase) == -1) { errMsg = "请上传扩展名为:" + fileFilter + "的图片"; return false; } return true; } /// /// 上传用户图片 /// /// /// /// /// public static string UpLoadUserPic(HttpPostedFile postedFile, string uCode, out string errMsg) { //检测成功 if (CheckImage(postedFile, out errMsg)) { try { using (Image im = Image.FromStream(postedFile.InputStream)) { //if (im.Width > 800 && im.Height > 700) //{ // errMsg = "上传图片的宽度和高度不能超过800(宽)*700(高)"; // return ""; //} //自定义图片名 string fileName = uCode; string _imgPath = UserPicPath; directoryChkMD(_imgPath); string _imgFile = Path.Combine(_imgPath, fileName + pubExt); ImageMaker.ToThumbnailImages(im, _imgFile, 120, 110); return fileName + pubExt; } } catch { errMsg = "对不起,上传照片发生错误!"; } } return ""; } } }