.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
    }

理论效果:


原测试图:


效果:




相关文章
|
3月前
|
数据安全/隐私保护
.net给图片增加水印和生成图片缩略图
.net给图片增加水印和生成图片缩略图
33 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
42 0
|
1月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
29 0
|
1月前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
5 0
|
1月前
|
开发框架 前端开发 .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,然后在重定向到另
99 5
|
3月前
|
XML 前端开发 定位技术
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
25 0
|
3月前
|
前端开发
.net core mvc获取IP地址和IP所在地(其实是百度的)
.net core mvc获取IP地址和IP所在地(其实是百度的)
124 0
|
8月前
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
116 0
|
9月前
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(一)
[回馈]ASP.NET Core MVC开发实战之商城系统(一)
113 0
|
9月前
|
SQL 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(开篇)
[回馈]ASP.NET Core MVC开发实战之商城系统(开篇)
144 0