WEB开发网
开发学院WEB开发ASP.NET asp.net mvc 3.0 动态无损图片压缩,及路由定义 阅读

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

 2012-07-06 22:41:47 来源:WEB开发网   
核心提示:/// <param name="height">高度</param>/// <param name="width"></param>/// <param name="quality">压缩质量 1-
/// <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 ow = iSource.Width;
int oh = 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)
{
oh = iSource.Height;
ow = iSource.Height * towidth / toheight;
y = 0;
x = (iSource.Width - ow) / 2;
}
else
{
ow = iSource.Width;
oh = iSource.Width * height / towidth;
x = 0;
y = (iSource.Height - oh) / 2;
}
break;
}
default:
break;
}

Bitmap ob = new Bitmap(towidth, toheight);
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, iSource.Width, iSource.Height)
, 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);
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];

Tags:asp net mvc

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接