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();
        }
    }

上传图片+生成缩略图 ashx代码的更多相关文章

  1. asp.net——上传图片生成缩略图

    上传图片生成缩略图,原图和缩略图地址一样的时候缩略图会把原图覆盖掉 /// <summary> /// 生成缩略图 /// </summary> /// <param n ...

  2. 使用Uploadify实现上传图片生成缩略图例子,实时显示进度条

    不了解Uploadify的,先看看前一篇详细说明 http://www.cnblogs.com/XuebinDing/archive/2012/04/26/2470995.html Uploadify ...

  3. ThinkPHP5.0图片上传生成缩略图实例代码

    很多朋友遇到这样一个问题,图片上传生成缩略图,很多人在本机(win)测试成功,上传到linux 服务器后错误. 我也遇到同样的问题.网上一查,有无数的人说是服务器临时文件目录权限问题. 几经思考后,发 ...

  4. ASP.NET生成缩略图的代码

    01.        // <summary> 02.        /// 生成缩略图 03.        /// </summary> 04.        /// &l ...

  5. tp3.2上传图片生成缩略图

    //引入 use think\Image; /* * $name为表单上传的name值 * $filePath为为保存在入口文件夹public下面uploads/下面的文件夹名称,没有的话会自动创建 ...

  6. C#上传图片同时生成缩略图,控制图片上传大小。

    #region 上传图片生成缩略图 /// <summary> /// 上传图片 /// </summary> /// <param name="sender& ...

  7. ASP组件AspJpeg(加水印)生成缩略图等使用方法

    ASP组件AspJpeg(加水印)生成缩略图等使用方法 作者: 字体:[增加 减小] 类型:转载 时间:2012-12-17我要评论 ASPJPEG是一款功能相当强大的图象处理组件,用它可以轻松地做出 ...

  8. C#生成缩略图不清晰模糊问题的解决方案!

    之前网上找了个生成缩略图的代码,改了改直接用了.问题来了,等比例缩略图时总是发现左边.上边的边线大概有一像素的白边,领导不乐意了,那咱就改吧.图片放大了才发现,那个好像是渐变的颜色,晕,这样的功能领导 ...

  9. js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能

    html: <form action="<{:AppLink('circle/uploadimg')}>" id="imageform" me ...

随机推荐

  1. Android 线程池系列教程(5)与UI线程通信要用Handler

    Communicating with the UI Thread 上一课 下一课 1.This lesson teaches you to Define a Handler on the UI Thr ...

  2. 1-最全CSS3选择器

    一,CSS3 选择器分类 二,选择器语法 1,基本选择器语法 选择器 类型 功能描述 *  通配选择器  选择文档中所以HTML元素 E  元素选择器 选择指定类型的HTML元素 #id  ID选择器 ...

  3. ASP.NET MVC+Bootstrap个人博客之文章打赏(六)

    看到新浪微博.百度百家等等平台上都带有文章“打赏”功能,觉得很新鲜,于是也想在自己的博客中加入“打赏”功能. 当然,加入打赏功能并非是真的想要让别人打赏.因为只有那些真正能引起共鸣,发人深思,让人受益 ...

  4. 面相切面编程AOP以及在Unity中的实现

    一.AOP概念 AOP(Aspect-Oriented Programming,面向切面的编程),它是可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术.它是 ...

  5. AJPFX关于File类复习

    file是一个路径,分为相对路径(eclipse)和绝对路径:1.构造方法有:File(String pathname ),File(String parent ,String child),File ...

  6. AJPFX:学习JAVA程序员两个必会的冒泡和选择排序

    * 数组排序(冒泡排序)* * 冒泡排序: 相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处* * 选择排序 : 从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现 ...

  7. 微信小程序组件解读和分析:六、progress进度条

    progress进度条组件说明: 进度条,就是表示事情当前完成到什么地步了,可以让用户视觉上感知事情的执行.progress进度条是微信小程序的组件,和HTML5的进度条progress类似. pro ...

  8. InChatter系统开源聊天模块前奏曲

    最近在研究WCF,又因为工作中的项目需要,要为现有的系统增加一个聊天模块以及系统消息提醒等,因此就使用WCF做服务器端开发了一个简单的系统. 开发最初学习了东邪孤独大哥的<传说的WCF系列> ...

  9. 解剖嵌入式设备开发时以SD卡启动时SD卡的存储结构(以三星exynos4412为例)

    目前面对高性能产品的嵌入式开发中,用SD卡来代替以往的JLINK显得备受大家喜欢,而且MCU厂家也对以SD卡启动的支持度越来越大,反而对JLINK不在那么重视(不过依旧保留着).一些以开发开发板的公司 ...

  10. CAD绘制二维码(网页版)

    js中实现代码说明: //新建一个COM组件对象 参数为COM组件类名 var getPt = mxOcx.NewComObject("IMxDrawUiPrPoint"); ge ...