生成图片缩略图

使用以下原创代码请遵循协议.
 
MakeThumb

 

 

MakeThumb
public static void MakeThumb(string frompath, string topath, int towidth, int toheight, double percent)
{
    Image img 
= Image.FromFile(frompath);

    
int width = 0;
    
int height = 0;

    
//todo: determine if the img is smaller than thumb
    if (img.Width > img.Height)
    {
        height 
= Convert.ToInt16(img.Height * percent);
        width 
= height * towidth / toheight;
    }
    
else
    {
        width 
= Convert.ToInt16(img.Width * percent);
        height 
= width * toheight / towidth;
    }

    
int x = (img.Width - width) / 2;
    
int y = (img.Height - height) / 2

    Image bitmap 
= new Bitmap(towidth, toheight);
    Graphics g 
= Graphics.FromImage(bitmap);
    g.InterpolationMode 
= InterpolationMode.High;
    g.SmoothingMode 
=SmoothingMode.HighQuality;
    g.Clear(Color.Transparent);

    g.DrawImage(img,
                
new Rectangle(00, towidth, toheight),
                
new Rectangle(x, y, width, height),
                GraphicsUnit.Pixel);
    
    
try
    {
        bitmap.Save(topath, ImageFormat.Jpeg);
    }
    
catch (System.Exception e)
    {
        
throw e;
    }
    
finally
    {
        img.Dispose();
        bitmap.Dispose();
        g.Dispose();
    }
}

 

园子里讲如何生成缩略图的文章和代码比比皆是,但是还是觉得自己用过的,修改过的更实在一点.对知根知底的东西本能地觉得多些信赖,呵呵.

posted @ 2010-05-07 13:58  杨圣青  阅读(367)  评论(2编辑  收藏  举报