View Code
/// <summary>
/// 缩略图
/// </summary>
/// <param name="srcImage">要缩略的图片</param>
/// <param name="thumSize">要缩放的尺寸</param>
/// <param name="mode">缩略模式</param>
/// <param name="alignment">对齐方式</param>
/// <returns>返回已经缩放的图片。</returns>
public static Bitmap GetDistortionlessThumbnailImage(Image srcImage, SizeF thumSize, ThumbnailMode mode, ContentAlignment alignment)
{
//先取宽比例。
float scale = (float)srcImage.Width / (float)thumSize.Width;
//缩略模式
switch (mode)
{
case ThumbnailMode.FullDistortionless:
if (srcImage.Height > srcImage.Width)
{
scale = (float)srcImage.Height / (float)thumSize.Height;
}
break;
case ThumbnailMode.MaxDistortionless:
if (srcImage.Height / scale < thumSize.Height)
{
scale = (float)srcImage.Height / (float)thumSize.Height;
}
break;
}
SizeF newSzie = new SizeF(srcImage.Width / scale, srcImage.Height / scale);
Bitmap result = new Bitmap((int)thumSize.Width, (int)thumSize.Height);
using (Graphics g = Graphics.FromImage(result))
{
//背景颜色
g.FillRectangle(Brushes.White, new RectangleF(PointF.Empty, thumSize));
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingMode = CompositingMode.SourceOver;
g.CompositingQuality = CompositingQuality.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
//对齐方式
RectangleF destRect;
switch (alignment)
{
case ContentAlignment.TopCenter:
destRect = new RectangleF(new PointF(-((newSzie.Width - thumSize.Width) / 2), 0), newSzie);
break;
case ContentAlignment.TopRight:
destRect = new RectangleF(new PointF(-(newSzie.Width - thumSize.Width), 0), newSzie);
break;
case ContentAlignment.MiddleLeft:
destRect = new RectangleF(new PointF(0, -((newSzie.Height - thumSize.Height) / 2)), newSzie);
break;
case ContentAlignment.MiddleCenter:
destRect = new RectangleF(new PointF(-((newSzie.Width - thumSize.Width) / 2), -((newSzie.Height - thumSize.Height) / 2)), newSzie);
break;
case ContentAlignment.MiddleRight:
destRect = new RectangleF(new PointF(-(newSzie.Width - thumSize.Width), -((newSzie.Height - thumSize.Height) / 2)), newSzie);
break;
case ContentAlignment.BottomLeft:
destRect = new RectangleF(new PointF(0, -(newSzie.Height - thumSize.Height)), newSzie);
break;
case ContentAlignment.BottomCenter:
destRect = new RectangleF(new PointF(-((newSzie.Width - thumSize.Width) / 2), -(newSzie.Height - thumSize.Height)), newSzie);
break;
case ContentAlignment.BottomRight:
destRect = new RectangleF(new PointF(-(newSzie.Width - thumSize.Width), -(newSzie.Height - thumSize.Height)), newSzie);
break;
default:
destRect = new RectangleF(PointF.Empty, newSzie);
break;
}
g.DrawImage(srcImage, destRect, new RectangleF(PointF.Empty, srcImage.Size), GraphicsUnit.Pixel);
g.Dispose();
}
return result;
}