您的位置:首页 > 编程语言 > ASP

Asp.net 生成高清缩略图

2013-12-17 18:28 405 查看

Asp.net 生成高清缩略图

    生成高清缩略图,原创代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;

namespace WebApplication
{
public class Images
{
#region 生成缩略图(图片压缩裁剪)
/// <summary>
/// 生成缩略图(图片压缩裁剪)
/// </summary>
/// <param name="serverImagePath">原始图片地址</param>
/// <param name="thumbnailImagePath">新图保存地址</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <param name="p">操作类型</param>
/// <param name="type">图片类型</param>
public static void GetThumbnail(string serverImagePath, string thumbnailImagePath, int width, int height, string p, string type)
{
Image serverImage = Image.FromFile(serverImagePath);

//画板大小
int towidth = width;
int toheight = height;

//缩略图矩形框的像素点
int x = 0;
int y = 0;
int ow = serverImage.Width;
int oh = serverImage.Height;

switch (p)
{
case "WH"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = serverImage.Height * width / serverImage.Width;
break;
case "H"://指定高,宽按比例
towidth = serverImage.Width * height / serverImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)serverImage.Width / (double)serverImage.Height > (double)towidth / (double)toheight)
{
oh = serverImage.Height;
ow = serverImage.Height * towidth / toheight;
y = 0;
x = (serverImage.Width - ow) / 2;
}
else
{
ow = serverImage.Width;
oh = serverImage.Width * height / towidth;
x = 0;
y = (serverImage.Height - oh) / 2;
}
break;
default:
break;
}

//新建一个bmp图片
Image bm = new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
Graphics g = Graphics.FromImage(bm);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(serverImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
System.Drawing.Imaging.ImageFormat imgtype = null;
switch (type)
{
case ".jpg":
case ".jpeg":
imgtype = System.Drawing.Imaging.ImageFormat.Jpeg;
break;
case ".gif":
imgtype = System.Drawing.Imaging.ImageFormat.Gif;
break;
case ".png":
imgtype = System.Drawing.Imaging.ImageFormat.Png;
break;
case "*.bmp":
imgtype = System.Drawing.Imaging.ImageFormat.Bmp;
break;
default:
imgtype = System.Drawing.Imaging.ImageFormat.Jpeg;
break;
}

//保存缩略图
bm.Save(thumbnailImagePath, imgtype);
}
catch (System.Exception e)
{
throw e;
}
finally
{
serverImage.Dispose();
bm.Dispose();
g.Dispose();
}
}
#endregion
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图片 压缩 bmp string switch