.net mvc中上传图片生成缩略图

简介:         #region CreateThumbnail         ///         /// 生成缩略图         ///         /// 上传的HttpPostedFile或图片物理路径         /// 上传文件夹相对路径         /// 后缀(如:.
        #region CreateThumbnail
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="uploadObject">上传的HttpPostedFile或图片物理路径</param>
        /// <param name="uploaddir">上传文件夹相对路径</param>
        /// <param name="ext">后缀(如:.jpg)</param>
        /// <param name="t_width">缩略图宽</param>
        /// <param name="t_height">缩略图高</param>
        /// <param name="filename">文件夹,不含路径和后缀</param>
        /// <param name="tm">枚举类-缩略图的样式</param>
        /// <returns>返回生成图片的路径</returns>
        public static string CreateThumbnail(object uploadObject, string uploaddir, string ext, int t_width, int t_height, string filename, ThumbModel tm)
        {
            System.Drawing.Image thumbnail_image = null;
            System.Drawing.Image original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = null;
            string ThumbnailFilename = "";
            try
            {
                if (uploadObject is HttpPostedFileBase)
                {
                    HttpPostedFileBase jpeg_image_upload = uploadObject as HttpPostedFileBase;
                    original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
                }
                else if (uploadObject is HttpPostedFile)
                {
                    HttpPostedFile jpeg_image_upload = uploadObject as HttpPostedFile;
                    original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
                }
                else
                {
                    string jpeg_image_upload = uploadObject as string;
                    original_image = System.Drawing.Image.FromFile(jpeg_image_upload);
                }
                // Calculate the new width and height
                int original_paste_x = 0;
                int original_paste_y = 0;
                int original_width = original_image.Width;//截取原图宽度
                int original_height = original_image.Height;//截取原图高度
                int target_paste_x = 0;
                int target_paste_y = 0;
                int target_width1 = t_width;
                int target_height1 = t_height;
                if (tm == ThumbModel.NoDeformationAllThumb)
                {
                    float target_ratio = (float)t_width / (float)t_height;//缩略图 宽、高的比例
                    float original_ratio = (float)original_width / (float)original_height;//原图 宽、高的比例

                    if (target_ratio > original_ratio)//宽拉长
                    {
                        target_height1 = t_height;
                        target_width1 = (int)Math.Floor(original_ratio * (float)t_height);
                    }
                    else
                    {
                        target_height1 = (int)Math.Floor((float)t_width / original_ratio);
                        target_width1 = t_width;
                    }

                    target_width1 = target_width1 > t_width ? t_width : target_width1;
                    target_height1 = target_height1 > t_height ? t_height : target_height1;
                    target_paste_x = (t_width - target_width1) / 2;
                    target_paste_y = (t_height - target_height1) / 2;
                }
                else if (tm == ThumbModel.NoDeformationCenterThumb)
                {
                    float target_ratio = (float)t_width / (float)t_height;//缩略图 宽、高的比例
                    float original_ratio = (float)original_width / (float)original_height;//原图 宽、高的比例

                    if (target_ratio > original_ratio)//宽拉长
                    {
                        original_height = (int)Math.Floor((float)original_width / target_ratio);
                    }
                    else
                    {
                        original_width=(int)Math.Floor((float)original_height * target_ratio);
                    }
                    original_paste_x = (original_image.Width - original_width) / 2;
                    original_paste_y = (original_image.Height - original_height) / 2;
                }
                else if(tm == ThumbModel.NoDeformationCenterBig)
                {
                    original_paste_x = (original_width - target_width1) / 2;
                    original_paste_y = (original_height - target_height1) / 2;
                    if(original_height>target_height1) original_height=target_height1;
                    if (original_width > target_width1) original_width = target_width1;
                }

                final_image = new System.Drawing.Bitmap(t_width, t_height);
                graphic = System.Drawing.Graphics.FromImage(final_image);
               // graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, t_width, t_height));//背景颜色

                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; /* new way */
                graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphic.Clear(Color.White);//背景
                Rectangle SrcRec = new Rectangle(original_paste_x, original_paste_y, original_width, original_height);
                Rectangle targetRec = new Rectangle(target_paste_x, target_paste_y, target_width1, target_height1);
                graphic.DrawImage(original_image, targetRec, SrcRec, GraphicsUnit.Pixel);
                string saveFileName = uploaddir + filename + "_small" + ext;
                using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("/" + saveFileName), FileMode.Create))
                {
                    final_image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ThumbnailFilename = saveFileName;
                }
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                HttpContext.Current.Response.StatusCode = 500;
                HttpContext.Current.Response.Write("An error occured");
                HttpContext.Current.Response.End();
            }
            finally
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (thumbnail_image != null) thumbnail_image.Dispose();
                if (ms != null) ms.Close();
            }
            return ThumbnailFilename;
        }

        #endregion


    public enum ThumbModel
    {
        /// <summary>
        /// 不变形,全部(缩略图)
        /// </summary>
        NoDeformationAllThumb,
        /// <summary>
        /// 变形,全部填充(缩略图)
        /// </summary>
        DeformationAllThumb,
        /// <summary>
        /// 不变形,截中间(缩略图)
        /// </summary>
        NoDeformationCenterThumb,
        /// <summary>
        /// 不变形,截中间(非缩略图)
        /// </summary>
        NoDeformationCenterBig
    }

理论效果:


原测试图:


效果:




相关文章
|
7月前
|
数据安全/隐私保护
.net给图片增加水印和生成图片缩略图
.net给图片增加水印和生成图片缩略图
76 0
|
3月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
51 7
|
3月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
82 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
60 0
|
4月前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
|
4月前
|
开发框架 .NET
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
151 0
|
7月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
214 0
|
6月前
|
前端开发 Java Maven
如何在Spring MVC中实现图片的上传和下载功能
如何在Spring MVC中实现图片的上传和下载功能
|
7月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
87 0
|
7月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
365 5