代码改变世界

ASP.NET MVC 中最简单的上传图片、生成缩略图的小例子

2011-04-25 14:54  音乐让我说  阅读(3530)  评论(1编辑  收藏  举报

直接贴代码:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    TestUpload
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        TestUpload</h2>
    <p>
        上传结果:<br />
        <%= ViewData["uploadResult"]  %>
    </p>
    <% using (Html.BeginForm("TestUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
       {
    %>
    <input name="upImg" type="file" /> <input type="submit" value="确定上传" />
    <%
        } %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
        [HttpPost]
        public ActionResult TestUpload(HttpPostedFileBase upImg)
        {
            string filePhysicalPath = Server.MapPath("~/Content/" + System.IO.Path.GetFileName(upImg.FileName));
            upImg.SaveAs(filePhysicalPath);
            string result = "ContentLength:" + upImg.ContentLength + "<br/>ContentType:" + upImg.ContentType + "<br/>FileName:" + upImg.FileName;
            string newFilePhysicalPath = Server.MapPath("~/Content/" + DateTime.Now.ToString("yyyyMMddHHmmssmmm"));
            SaveThumbnailImage(filePhysicalPath, newFilePhysicalPath, 80, 60);
            ViewData["uploadResult"] = result;
            return View();
        }

          

源码如下:

    /// <summary>
    /// 图片帮助累
    /// </summary>
    public static class ImageHelper
    {
        /// <summary>
        /// 缩略图配置类
        /// </summary>
        public class ThumbnailImageOptions
        {
            /// <summary>
            /// 目标文件的路径
            /// </summary>
            public string TargetFileName { get; set; }

            /// <summary>
            /// 宽度
            /// </summary>
            public int Width { get; set; }

            /// <summary>
            /// 高度
            /// </summary>
            public int Height { get; set; }
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="srcFileName">原始文件</param>
        /// <param name="targetFileName">目标文件,不能和原始文件的路径相同</param>
        /// <param name="width">图宽度</param>
        /// <param name="heigth">图高度</param>
        public static bool SaveThumbnailImage(string srcFileName, string targetFileName, int width, int heigth)
        {
            if (srcFileName == null)
            {
                throw new ArgumentNullException("srcFileName");
            }
            if (targetFileName == null)
            {
                throw new ArgumentNullException("targetFileName");
            }
            return SaveThumbnailImage(srcFileName, new ThumbnailImageOptions[] 
            { 
                new ThumbnailImageOptions(){ TargetFileName = targetFileName, Width = width, Height = heigth } 
            });
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="srcFileName">图片源文件的路径</param>
        /// <param name="optionItems">一个或多个配置</param>
        /// <returns></returns>
        public static bool SaveThumbnailImage(string srcFileName, IEnumerable<ThumbnailImageOptions> optionItems)
        {
            if (srcFileName == null)
            {
                throw new ArgumentNullException("srcFileName");
            }
            if (optionItems == null)
            {
                throw new ArgumentNullException("items");
            }
            if (!optionItems.Any())
            {
                return true;
            }
            using (FileStream fs = new FileStream(srcFileName, FileMode.Open))
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                try
                {
                    foreach (ThumbnailImageOptions item in optionItems)
                    {
                        System.Drawing.Image newThumImg = img.GetThumbnailImage(item.Width, item.Height, null, IntPtr.Zero);
                        newThumImg.Save(item.TargetFileName);
                        newThumImg.Dispose();
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    img.Dispose();
                }
            }
        }
    }

 谢谢浏览!