代码改变世界

生成缩略图的方法

2011-08-23 10:37  刘朝  阅读(163)  评论(0)    收藏  举报

一个生成缩略图的方法,呵呵。

public Bitmap CreateThumbnail(Bitmap originalBmp, int desiredWidth, int desiredHeight)
{
     if (originalBmp.Width <= desiredWidth && originalBmp.Height <= desiredHeight)
    {
        return originalBmp;
    }

    int newWidth, newHeight;

    if ((decimal)desiredWidth / originalBmp.Width < (decimal)desiredHeight / originalBmp.Height)
    {
        decimal desiredRatio = (decimal)desiredWidth / originalBmp.Width;
        newWidth = desiredWidth;
        newHeight = (int)(originalBmp.Height * desiredRatio);
    }
    else
    {
        decimal desiredRatio = (decimal)desiredHeight / originalBmp.Height;
        newHeight = desiredHeight;
        newWidth = (int)(originalBmp.Width * desiredRatio);
    }

     Bitmap bmpOut = new Bitmap(newWidth, newHeight);

    using (Graphics graphics = Graphics.FromImage(bmpOut))
    {
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
        graphics.DrawImage(originalBmp, 0, 0, newWidth, newHeight);
    }

    return bmpOut;
}