asp.net mvc 3.0 动态无损图片压缩,及路由定义

最新更新:120821

1.定义路由

2.编写控制器

3.编写图片压缩方法

4.测试运行

---------------------------------------------------

1.定义路由 ,一般写在 Globals.cs 文件中

      routes.MapRoute(
          "ImgRoute", // 图片路由名称
          "pics/{thumbnailType}/{width}/{height}/{*imgPath}", // 带有参数的 URL
          new { controller = "Pictures", action = "ZoomImg", id = UrlParameter.Optional }, // 参数默认值
          nameSpace);

2.编写控制器

  public class ImagesController : Controller
  {
   

    /// <summary>
    /// 缩放图片
    /// </summary>
    /// <param name="thumbnailType">图片缩放方式(取值参考:EB.Sys.Images.ImgThumbnail.ImgThumbnailType 枚举值)</param>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    /// <param name="imgPath">图片路径</param>
    /// <returns></returns>
    public string ZoomImg(string thumbnailType, string width, string height, string imgPath)
    {
      //return string.Format("{0} : {1} , {2} , {3} , {4}"
      //  ,DateTime.Now
      //  ,thumbnailType
      //  ,width
      //  ,height
      //  ,imgPath);

      string sourceFile = Server.MapPath(string.Format("~/{0}", imgPath));

      if (!System.IO.File.Exists(sourceFile))
        return string.Format("图片路径无效:{0}", sourceFile);

      ImgThumbnail.ImgThumbnailType type = (ImgThumbnail.ImgThumbnailType)thumbnailType.GetInt();

      if (type == ImgThumbnail.ImgThumbnailType.Nothing)
        return string.Format("压缩类型错误:{0}", thumbnailType);

      EB.Sys.Images.ImgThumbnail.Thumbnail(
        sourceFile
        , Response.OutputStream
        , width.GetInt()
        , height.GetInt()
        , 90
        , type);
      //测试输出流中是否存在内容
      //byte[] arr = new byte[1000];
      //Response.OutputStream.Write(arr,0,arr.Length);
      return string.Empty;
    }


  }

 

3.编写图片压缩方法

这个方法在我另外一篇文章中有介绍,这里做了个加工

http://blog.csdn.net/xxj_jing/article/details/7715729

 

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace EB.Sys.Images
{
  /// <summary>
  /// 图片压缩
  /// </summary>
  public class ImgThumbnail
  {
    #region 枚举
    /// <summary>
    /// 指定缩放类型
    /// </summary>
    public enum ImgThumbnailType
    {
      /// <summary>
      /// 无
      /// </summary>
      Nothing=0,
      /// <summary>
      /// 指定高宽缩放(可能变形)
      /// </summary>
      WH = 1,
      /// <summary>
      /// 指定宽,高按比例
      /// </summary>
      W = 2,
      /// <summary>
      /// 指定高,宽按比例
      /// </summary>
      H = 3,
      /// <summary>
      /// 指定高宽裁减(不变形)
      /// </summary>
      Cut = 4,
      /// <summary>
      /// 按照宽度成比例缩放后,按照指定的高度进行裁剪
      /// </summary>
      W_HCut = 5,
    }
    #endregion

    #region 图片压缩
    /// <summary>
    /// 无损压缩图片
    /// </summary>
    /// <param name="sourceFile">原图片</param>
    /// <param name="stream">压缩后保存到流中</param>
    /// <param name="height">高度</param>
    /// <param name="width"></param>
    /// <param name="quality">压缩质量 1-100</param>
    /// <param name="type">压缩缩放类型</param>
    /// <returns></returns>
    private static Bitmap Thumbnail(string sourceFile, int width, int height, int quality
      , ImgThumbnailType type, out ImageFormat tFormat)
    {
      using (System.Drawing.Image iSource = System.Drawing.Image.FromFile(sourceFile))
      {
        tFormat = iSource.RawFormat;
        //缩放后的宽度和高度
        int toWidth = width;
        int toHeight = height;
        //
        int x = 0;
        int y = 0;
        int oWidth = iSource.Width;
        int oHeight = iSource.Height;

        switch (type)
        {
          case ImgThumbnailType.WH://指定高宽缩放(可能变形)           
            {
              break;
            }
          case ImgThumbnailType.W://指定宽,高按比例     
            {
              toHeight = iSource.Height * width / iSource.Width;
              break;
            }
          case ImgThumbnailType.H://指定高,宽按比例
            {
              toWidth = iSource.Width * height / iSource.Height;
              break;
            }
          case ImgThumbnailType.Cut://指定高宽裁减(不变形)     
            {
              if ((double)iSource.Width / (double)iSource.Height > (double)toWidth / (double)toHeight)
              {
                oHeight = iSource.Height;
                oWidth = iSource.Height * toWidth / toHeight;
                y = 0;
                x = (iSource.Width - oWidth) / 2;
              }
              else
              {
                oWidth = iSource.Width;
                oHeight = iSource.Width * height / toWidth;
                x = 0;
                y = (iSource.Height - oHeight) / 2;
              }
              break;
            }
          case ImgThumbnailType.W_HCut://按照宽度成比例缩放后,按照指定的高度进行裁剪
            {
              toHeight = iSource.Height * width / iSource.Width;
              if (height < toHeight)
              {
                oHeight = oHeight * height / toHeight;
                toHeight = toHeight * height / toHeight;
              }
              break;
            }
          default:
            break;
        }

        Bitmap ob = new Bitmap(toWidth, toHeight);
        //ImgWaterMark iwm = new ImgWaterMark();
        //iwm.AddWaterMark(ob, towidth, toheight, "www.***.com");
        Graphics g = Graphics.FromImage(ob);
        g.Clear(System.Drawing.Color.WhiteSmoke);
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(iSource
          , new Rectangle(x, y, toWidth, toHeight)
          , new Rectangle(0, 0, oWidth, oHeight)
          , GraphicsUnit.Pixel);
        g.Dispose();

        return ob;
       
      }
    }
    /// <summary>
    /// 无损压缩图片
    /// </summary>
    /// <param name="sourceFile">原图片</param>
    /// <param name="stream">压缩后保存到流中</param>
    /// <param name="height">高度</param>
    /// <param name="width"></param>
    /// <param name="quality">压缩质量 1-100</param>
    /// <param name="type">压缩缩放类型</param>
    /// <returns></returns>
    public static bool Thumbnail(string sourceFile, System.IO.Stream stream,  int width,int height, int quality, ImgThumbnailType type)
    {
      ImageFormat tFormat = null;
      Bitmap ob = Thumbnail(sourceFile, width, height, quality, type, out tFormat);
      //水印
      ImgWaterMark.AddWaterMark(ob, "www.***.com");
      //以下代码为保存图片时,设置压缩质量
      EncoderParameters ep = new EncoderParameters();
      long[] qy = new long[1];
      qy[0] = quality;//设置压缩的比例1-100
      EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
      ep.Param[0] = eParam;
      try
      {
        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo jpegICIinfo = null;
        for (int i = 0; i < arrayICI.Length; i++)
        {
          if (arrayICI[i].FormatDescription.Equals("JPEG"))
          {
            jpegICIinfo = arrayICI[i];
            break;
          }
        }
        if (jpegICIinfo != null)
        {
          ob.Save(stream, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
        }
        else
        {
          ob.Save(stream, tFormat);
        }
        return true;
      }
      catch
      {
        return false;
      }
      finally
      {
        //iSource.Dispose();

        ob.Dispose();

      }
    }

    /// <summary>
    /// 无损压缩图片
    /// </summary>
    /// <param name="sourceFile">原图片</param>
    /// <param name="targetFile">压缩后保存位置</param>
    /// <param name="height">高度</param>
    /// <param name="width"></param>
    /// <param name="quality">压缩质量 1-100</param>
    /// <param name="type">压缩缩放类型</param>
    /// <returns></returns>
    public static bool Thumbnail(string sourceFile, string targetFile, int width, int height, int quality, ImgThumbnailType type)
    {
      ImageFormat tFormat = null;
      Bitmap ob = Thumbnail(sourceFile, width, height, quality, type, out tFormat);
      //以下代码为保存图片时,设置压缩质量
      EncoderParameters ep = new EncoderParameters();     
      long[] qy = new long[1];
      qy[0] = quality;//设置压缩的比例1-100
      EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
      ep.Param[0] = eParam;
      try
      {
        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo jpegICIinfo = null;
        for (int i = 0; i < arrayICI.Length; i++)
        {
          if (arrayICI[i].FormatDescription.Equals("JPEG"))
          {
            jpegICIinfo = arrayICI[i];
            break;
          }
        }
        if (jpegICIinfo != null)
        {
          ob.Save(targetFile, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
        }
        else
        {
          ob.Save(targetFile, tFormat);
        }
        return true;
      }
      catch
      {
        return false;
      }
      finally
      {
        //iSource.Dispose();

        ob.Dispose();

      }
    }
    #endregion

  }
}

  

4.测试运行

www.****.com/pics/5/195/395/images/ShangZhuang/610505/610505_00--w_498_h_498.jpg

在看一下路由定义:

 " pics/{thumbnailType}/{width}/{height}/{*imgPath}"

 {thumbnailType} 匹配 5

 {width} 匹配 195

{height} 匹配 395

{*imgPath} 匹配 images/ShangZhuang/610505/610505_00--w_498_h_498.jpg

和控制器中的方法:

  public string ZoomImg(string thumbnailType, string width, string height, string imgPath)

你明白的!参数列表命名相同!

 

转载保留:http://write.blog.csdn.net/postedit/7723502

 

posted @ 2012-07-06 21:58  草青工作室  阅读(420)  评论(0编辑  收藏  举报