| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 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);
- }
- }
- /// <summary>
- /// 检测图片是否符合
- /// </summary>
- /// <param name="postedFile"></param>
- /// <param name="errMsg"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 上传用户图片
- /// </summary>
- /// <param name="postedFile"></param>
- /// <param name="uCode"></param>
- /// <param name="errMsg"></param>
- /// <returns></returns>
- 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 "";
- }
- }
- }
|