本例中,对于不规则的宽高,进行了裁剪,保留中心内容
/// <summary>
/// 生成高质量小图
/// 参考:https://blog.csdn.net/lhtzbj12/article/details/54099246?spm=1001.2014.3001.5501
/// </summary>
/// <param name="originalImageLocalPath">原图本地全路径</param>
/// <param name="smallImageSize">小图尺寸</param>
/// <returns></returns>
public static Bitmap GenerateSmallImage(string originalImageLocalPath, Size smallImageSize)
{
// 原图不存在,返回false
if (string.IsNullOrWhiteSpace(originalImageLocalPath) || !FileHelper.IsImageFileExists(originalImageLocalPath))
{
return null;
}
Image img = null;
Graphics graphics = null;
try
{
img = Image.FromFile(originalImageLocalPath);
if (img.Size.Width == smallImageSize.Width && img.Size.Height == smallImageSize.Height)
{
return new Bitmap(img);
}
double sizeRatio = img.Width / (double)img.Height;
double standardRatio = smallImageSize.Width / (double)smallImageSize.Height;
Rectangle srcRect = new Rectangle(new Point(0, 0), img.Size);
// 高度占比偏大,需要裁剪高度:上下裁剪保留中间部分,宽度不变
if (sizeRatio < standardRatio)
{
// 获得裁剪后的高度
int cutedHeight = (int)(img.Width / standardRatio);
int cutedY = (img.Height - cutedHeight) / 2;
srcRect = new Rectangle(new Point(0, cutedY), new Size(img.Width, cutedHeight));
}
// 宽度占比偏大,需要裁剪宽度:左右裁剪保留中间部分,高度不变
if (sizeRatio > standardRatio)
{
// 获得裁剪后的宽度
int cutedwidth = (int)(img.Height * standardRatio);
int cutedX = (img.Width - cutedwidth) / 2;
srcRect = new Rectangle(new Point(cutedX, 0), new Size(cutedwidth, img.Height));
}
Bitmap bitmap = new Bitmap(smallImageSize.Width, smallImageSize.Height);
graphics = Graphics.FromImage(bitmap); // 从bitmap中获取图层
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.Default;
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
graphics.DrawImage(img, new Rectangle(Point.Empty, smallImageSize), srcRect, GraphicsUnit.Pixel); // 使用原图绘制
return bitmap;
}
catch
{
return null;
}
finally
{
img?.Dispose();
graphics?.Dispose();
}
}