html页面

<form action="Handlers/UploadImageHandler.ashx" method="post" enctype="multipart/form-data">
        <input type="file" name="image"/>
        <input type="hidden" value="web" name="directory" />
        <input type="submit" name="submitbtn" />
    </form>

//一般处理程序

public class PicUploadHander : IHttpHandler
    {

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //验证上传的权限TODO
            string _fileNamePath = "";
            try
            {
                _fileNamePath = context.Request.Files[0].FileName;
                //开始上传
                string _savedFileResult = UpLoadImage(_fileNamePath, context);
                context.Response.Write(_savedFileResult);
            }
            catch
            {
                context.Response.Write("上传提交出错");
            }
        }

public string UpLoadImage(string fileNamePath, HttpContext context)
        {
            try
            {
                string serverPath = System.Web.HttpContext.Current.Server.MapPath("~");

string toFilePath = Path.Combine(serverPath, @"Content\Upload\Images\");

//获取要保存的文件信息
                FileInfo file = new FileInfo(fileNamePath);
                //获得文件扩展名
                string fileNameExt = file.Extension;

//验证合法的文件
                if (CheckImageExt(fileNameExt))
                {
                    //生成将要保存的随机文件名
                    string fileName = GetImageName() + fileNameExt;

//获得要保存的文件路径
                    string serverFileName = toFilePath + fileName;
                    //物理完整路径                   
                    string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath);

//将要保存的完整文件名               
                    string toFile = toFileFullPath;//+ fileName;

///创建WebClient实例      
                    WebClient myWebClient = new WebClient();
                    //设定windows网络安全认证   方法1
                    myWebClient.Credentials = CredentialCache.DefaultCredentials;
                    ////设定windows网络安全认证   方法2
                    context.Request.Files[0].SaveAs(toFile);

//上传成功后网站内源图片相对路径
                    string relativePath = System.Web.HttpContext.Current.Request.ApplicationPath
                                          + string.Format(@"Content/Upload/Images/{0}", fileName);

/*
                      比例处理
                      微缩图高度(DefaultHeight属性值为 400)
                    */
                    System.Drawing.Image img = System.Drawing.Image.FromFile(toFile);
                    int width = img.Width;
                    int height = img.Height;
                    float ratio = (float)width / height;

//微缩图高度和宽度
                    int newHeight = height <= DefaultHeight ? height : DefaultHeight;
                    int newWidth = height <= DefaultHeight ? width : Convert.ToInt32(DefaultHeight * ratio);

FileInfo generatedfile = new FileInfo(toFile);
                    string newFileName = "Thumb_" + generatedfile.Name;
                    string newFilePath = Path.Combine(generatedfile.DirectoryName, newFileName);

PictureHandler.CreateThumbnailPicture(toFile, newFilePath, newWidth, newHeight);

string thumbRelativePath = System.Web.HttpContext.Current.Request.ApplicationPath
                                          + string.Format(@"/Content/Upload/Images/{0}", newFileName);

//返回原图和微缩图的网站相对路径
                    relativePath = string.Format("{0},{1}", relativePath, thumbRelativePath);

return relativePath;
                }
                else
                {
                    return "文件格式非法,请上传gif或jpg格式的文件。";
                    //throw new Exception("文件格式非法,请上传gif或jpg格式的文件。");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

public bool IsReusable
        {
            get
            {
                return false;
            }
        }

#region Private Methods
        /// <summary>
        /// 检查是否为合法的上传图片
        /// </summary>
        /// <param name="_fileExt"></param>
        /// <returns></returns>
        private bool CheckImageExt(string imageExt)
        {
            string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp" };
            //for (int i = 0; i < allowExt.Length; i++)
            //{
            //    if (allowExt[i] == _ImageExt) { return true; }
            //}

StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;

return allowExt.Any(c => stringComparer.Equals(c, imageExt));

}

private string GetImageName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            serial.Append(rd.Next(0, 999999).ToString());
            return serial.ToString();

}

public int DefaultHeight
        {
            get
            {
                //此处硬编码了,可以写入配置文件中。
                return 100;
            }
        }

#endregion
    }

//缩略图处理相关类

public static class PictureHandler
    {
        /// <summary>
        /// 图片微缩图处理
        /// </summary>
        /// <param name="srcPath">源图片</param>
        /// <param name="destPath">目标图片</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        public static void CreateThumbnailPicture(string srcPath, string destPath, int width, int height)
        {
            //根据图片的磁盘绝对路径获取 源图片 的Image对象
            System.Drawing.Image img = System.Drawing.Image.FromFile(srcPath);

//bmp: 最终要建立的 微缩图 位图对象。
            Bitmap bmp = new Bitmap(width, height);

//g: 绘制 bmp Graphics 对象
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.Transparent);
            //为Graphics g 对象 初始化必要参数,很容易理解。
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

//源图片宽和高
            int imgWidth = img.Width;
            int imgHeight = img.Height;

//绘制微缩图
            g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, imgWidth, imgHeight)
                        , GraphicsUnit.Pixel);

ImageFormat format = img.RawFormat;
            ImageCodecInfo info = ImageCodecInfo.GetImageEncoders().SingleOrDefault(i => i.FormatID == format.Guid);
            EncoderParameter param = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = param;
            img.Dispose();

//保存已生成微缩图,这里将GIF格式转化成png格式。
            if (format == ImageFormat.Gif)
            {
                destPath = destPath.ToLower().Replace(".gif", ".png");
                bmp.Save(destPath, ImageFormat.Png);
            }
            else
            {
                if (info != null)
                {
                    bmp.Save(destPath, info, parameters);
                }
                else
                {

bmp.Save(destPath, format);
                }
            }

img.Dispose();
            g.Dispose();
            bmp.Dispose();
        }
    }

最新文章

  1. WSDL2java简单使用
  2. iscroll 加载不全解决方案
  3. Java学习笔记 05 数据包装类
  4. C#计算文件的MD5值实例
  5. iOS 代理与block 逆向传值 学习
  6. ubuntu14.10服务器版安装xampp,配置域名端口访问
  7. JSP显示-下拉框
  8. Bugtags,产品经理的瑞士军刀
  9. Django下载中文名文件:
  10. Delphi XE5教程5:程序的结构和语法
  11. fluentd结合kibana、elasticsearch实时搜索分析hadoop集群日志&lt;转&gt;
  12. 【翻译】Organizing ASP.NET MVC solutions 如何组织你的ASP.NET MVC解决方案
  13. appium 学习各种小功能总结--功能有《滑动图片、保存截图、验证元素是否存在、》---新手总结(大牛勿喷,新手互相交流)
  14. thin-provisioning-tools
  15. Git建空白分支
  16. cocos2dx - v2.3.3编辑器简单使用及不同分辨率适配
  17. 工厂模式(Factory Method)
  18. Jamon
  19. mybatis 中使用 in 查询
  20. 最大矩阵(简单DP)

热门文章

  1. android 系统的时间间隔和睡眠用哪个?
  2. 最简单的struts实例介绍
  3. Oracle中默认创建的表
  4. 静态代理,jdbc动态代理和cglib动态代理
  5. java基础(六):RabbitMQ 入门
  6. AJPFX总结泛型概念和使用
  7. spark 学习路线及参考课程
  8. 【C++】异常简述(三):补充之如何看待C++异常
  9. Asp.Net 设计模式 之 “特殊”的单例模式
  10. Vim中文编码问题