ASP.NET C# 生成不失真的缩略图

来源:互联网 发布:史丹利快报淘宝 编辑:程序博客网 时间:2024/05/16 09:21

 

ASP.NET C# 生成不失真的缩略图[转]  

 

刚才看了下image类中提供的生成缩略图的方法GetThumbnailImage() 方法,发现失真比较严重,

在网上查了下资料,现在整理了一下,供大家参考!

后台代码:

protected void Bt5_Click(object sender, EventArgs e)
    {
        
string imgPath = this.File3.PostedFile.FileName;//完全名

        string imgName = imgPath.Substring(imgPath.LastIndexOf("\\"+ 1);
        
string imgEx = imgPath.Substring(imgPath.LastIndexOf("."+ 1
);
        
string math = Server.MapPath("upimg"
);//这里的upimg应该是在您的Web的根目录下创建一个文件夹用于存储图片文件

        
//使用了Image类提供的缩略图方法,但是失真

        System.Drawing.Image img1;
        
int
 height;
        
int
 width;
        img1 
= System.Drawing.Image.FromFile(imgPath, false);//加载图片到对象,并加入颜色管理信息(否则可能会出现偏色现像)

        int bl = Convert.ToInt32(img1.Height / 200);//取缩小比例
        height = Convert.ToInt32(img1.Height / bl);
        width 
= Convert.ToInt32(img1.Width /
 bl);

        
//
这里是.NET Framework提供的取缩略图方法
        
//img1.GetThumbnailImage(width, height, null, new IntPtr()).Save(math + "\\" + imgName);


        System.Drawing.Image hb 
= new System.Drawing.Bitmap(width, height);//创建图片对象
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(hb);//创建画板并加载空白图像
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;//设置保真模式为高度保真
        g.DrawImage(img1, new Rectangle(00, width, height), 00, img1.Width, img1.Height, GraphicsUnit.Pixel);//开始画图
        hb.Save(math + "\\" + imgName);
        g.Dispose();
        hb.Dispose();
        img1.Dispose();
    }

页面代码:

<input id="File3" type="file" runat="server" />
<asp:Button ID="Button5" runat="server" Text="Button" OnClick="Bt5_Click" />

原创粉丝点击