public void MakeThumbnail( string originalImagePath, string thumbnailPath, int width, int height)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
int bg_x = 0;
int bg_y = 0;
int bg_w = towidth;
int bg_h = toheight;
double multiple = 0;
if (originalImage.Width >= originalImage.Height)
multiple = ( double )originalImage.Width / ( double )width;
else
multiple = ( double )originalImage.Height / ( double )height;
if (ow <= width && oh <= height)
{
bg_w = originalImage.Width;
bg_h = originalImage.Height;
bg_x = Convert.ToInt32((( double )towidth - ( double )ow) / 2);
bg_y = Convert.ToInt32((( double )toheight - ( double )oh) / 2);
}
else
{
bg_w = Convert.ToInt32(( double )originalImage.Width / multiple);
bg_h = Convert.ToInt32(( double )originalImage.Height / multiple);
bg_y = Convert.ToInt32((( double )height - ( double )bg_h) / 2);
bg_x = Convert.ToInt32((( double )width - ( double )bg_w) / 2);
}
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(System.Drawing.ColorTranslator.FromHtml( "#F2F2F2" ));
g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
try
{
string fileExtension = System.IO.Path.GetExtension(originalImagePath).ToLower();
switch (fileExtension)
{
case ".gif" : bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break ;
case ".jpg" : bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break ;
case ".bmp" : bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break ;
case ".png" : bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break ;
}
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
posted @
2012-08-21 11:47
小女阿媚
阅读(
118 )
评论()
收藏
举报