asp.net生成缩略图示例方法分享

 更新时间:2013年12月31日 11:31:56   作者:  
asp.net快速生成清晰缩略图,大家参考使用吧

做站的时候经常会遇到要生成缩略图的功能,因为可能不同的情况需要用来不同大小的缩略图。

本文生成的图片都为正方形,只有正方形的缩略图才是保证图片足够清晰。

当我我这里说的正方形是先按比例压缩,然后加一个固定的白底 然后居中显示。

代码:

新建outputimg.ashx

复制代码 代码如下:

//调整图片大小
private static Size NewSize(int maxWidth, int maxHeight, int Width, int Height)
        {
            double w = 0.0;
            double h = 0.0;
            double sw = Convert.ToDouble(Width);
            double sh = Convert.ToDouble(Height);
            double mw = Convert.ToDouble(maxWidth);
            double mh = Convert.ToDouble(maxHeight);

            if (sw < mw && sh < mh)//如果maxWidth和maxHeight大于源图像,则缩略图的长和高不变
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = maxWidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = maxHeight;
                w = (h * sw) / sh;
            }
            return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }

复制代码 代码如下:

//生成缩略图
public static void SendSmallImage(string filename, string newfile, int maxHeight, int maxWidth, string mode)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(filename);//源图像的信息
            System.Drawing.Imaging.ImageFormat thisformat = img.RawFormat; //源图像的格式
            Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height); //返回调整后的图像Width与Height
            Bitmap outBmp = new Bitmap(maxWidth, maxHeight);
            Graphics g = Graphics.FromImage(outBmp);
            //设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.Clear(Color.White);
            g.DrawImage(img, new Rectangle(((maxWidth - newSize.Width) / 2), ((maxHeight - newSize.Height) / 2), newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            //获取包含有关内置图像编码解码器的信息的ImageCodecInfo对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置jpeg编码
                    break;
                }
            }
            if (jpegICI != null)
            {
                outBmp.Save(newfile, jpegICI, encoderParams);
            }
            else
            {
                outBmp.Save(newfile, thisformat);
            }
            img.Dispose();
            outBmp.Dispose();
        }

输出图片:

复制代码 代码如下:

//输出图片
        public static void OutPutImg(string imgFilePath)
        {
            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(imgFilePath), FileMode.Open, FileAccess.Read);
            DateTime contentModified = System.IO.File.GetLastWriteTime(HttpContext.Current.Server.MapPath(imgFilePath));
            if (IsClientCached(contentModified))
            {
                HttpContext.Current.Response.StatusCode = 304;
                HttpContext.Current.Response.SuppressContent = true;
            }
            else
            {
                byte[] mydata = new byte[fs.Length];
                int Length = Convert.ToInt32(fs.Length);
                fs.Read(mydata, 0, Length);
                fs.Close();
                HttpContext.Current.Response.OutputStream.Write(mydata, 0, Length);
                HttpContext.Current.Response.ContentType = "image/jpeg";
                HttpContext.Current.Response.End();
                HttpContext.Current.Response.Cache.SetETagFromFileDependencies();
                HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(true);
                HttpContext.Current.Response.Cache.SetLastModified(contentModified);
            }
        }

复制代码 代码如下:

//outpuimg.ashx?src=/images/weimeidesc/8af30049-797e-4eb4-8a54-cc4de47c1694.jpg!100x100.jpg
        public void ProcessRequest(HttpContext context)
        {
            //获取图片
            string imgUrl = context.Request.QueryString["src"];
            string trueFilePath = imgUrl.Split('!')[0];
            //获取图片大小
            int width = Convert.ToInt32(imgUrl.Split('!')[1].Replace(".jpg", "").Split('x')[0]);
            int height = Convert.ToInt32(imgUrl.Split('!')[1].Replace(".jpg", "").Split('x')[1]);

            //图片已经存在直接输出
            if (File.Exists(context.Server.MapPath("~/" + imgUrl)))
            {
                OutPutImg("~/"+imgUrl);
            }
            else
            {
                if (!string.IsNullOrEmpty(imgUrl) && File.Exists(context.Server.MapPath("~/" + trueFilePath)))
                {
                    Image originalImage = System.Drawing.Image.FromFile(context.Server.MapPath("~/" + trueFilePath));
                    var newBitmap = new Bitmap(originalImage);
                    //生成相应的小图并保存
                    SendSmallImage(context.Server.MapPath("~/" + trueFilePath),context.Server.MapPath("~/" + imgUrl), width, height, "meiyouyisi");
                    //输出
                    OutPutImg("~/" + imgUrl);
                }
                else//图片如果不存在 输出默认图片
                {
                    //OutPutImg(imgUrl);
                }
            }
        }

相关文章

  • 如何在Asp.Net Core中集成ABP Dapper

    如何在Asp.Net Core中集成ABP Dapper

    这篇文章主要介绍了如何在Asp.Net Core中集成ABP Dapper,帮助大家更好的理解和学习使用Asp.Net Core,感兴趣的朋友可以了解下
    2021-03-03
  • ASP.NET私有构造函数用法分析

    ASP.NET私有构造函数用法分析

    这篇文章主要介绍了ASP.NET私有构造函数用法,较为详细的分析了ASP.NET中私有构造函数的特性及具体用法,需要的朋友可以参考下
    2014-11-11
  • asp.net关于onpropertychange和oninput事件实现代码

    asp.net关于onpropertychange和oninput事件实现代码

    文本框,数据列表,当在文本框中输入条件时需要实时刷新数据列表,而且需要满足多浏览器(IE6.0/7.0/8.0,FireFox,Opera,google chrome,Safair)其功能类似google的智能匹配,我是用asp.net实现的。
    2009-11-11
  • ASP.NET 页面间数据传递方法小结

    ASP.NET 页面间数据传递方法小结

    Web 页面是无状态的, 服务器对每一次请求都认为来自不同用户,因此,变量的状态在连续对同一页面的多次请求之间或在页面跳转时不会被保留。
    2009-12-12
  • ASP.NET实现级联下拉框效果实例讲解

    ASP.NET实现级联下拉框效果实例讲解

    这篇文章主要为大家详细介绍了ASP.NET实现级联下拉框效果实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2015-09-09
  • .Net基于MVC4 Web Api输出Json格式实例

    .Net基于MVC4 Web Api输出Json格式实例

    这篇文章主要介绍了.Net基于MVC4 Web Api输出Json格式的实现方法,实例讲述了Global中json的操作与XML的处理等技巧,需要的朋友可以参考下
    2014-10-10
  • asp.net为网页动态添加关键词的方法

    asp.net为网页动态添加关键词的方法

    这篇文章主要介绍了asp.net为网页动态添加关键词的方法,可实现动态添加keyword meta的功能,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • Quartz.NET的具体使用

    Quartz.NET的具体使用

    本文详细的介绍了Quartz.NET的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • 给自定义Web控件添加事件(前后台代码)

    给自定义Web控件添加事件(前后台代码)

    给自定义控件(Web Control)添加事件具体前后台代码如下,感兴趣的朋友可以参考下哈
    2013-06-06
  • .net重启iis线程池和iis站点程序代码分享

    .net重启iis线程池和iis站点程序代码分享

    服务器监控,一定时间内或者iis异常就需要重启线程池和站点,下面我们用代码来做这个功能
    2013-12-12

最新评论