前几天做一个系统,想着用户上传头像时按照比例裁剪裁剪成固定大小,有时候用户上传的图片会很大,影响效率,因此在网上找了一个裁剪图片的方法:
#region 图片缩放
/// <summary>
/// c# asp.net 图片缩放[通用]
/// </summary>
/// <param name="sourcePath">要缩放图片路径</param>
/// <param name="savePath">缩放后图片路径</param>
/// <param name="w">最大的宽度</param>
/// <param name="h">最大的高度</param>
public static void ImageChange(string sourcePath, string savePath, int w, int h)
{
System.Drawing.Image _sourceImg = System.Drawing.Image.FromFile(sourcePath);
double _newW = (double)w, _newH = (double)h, t;
if ((double)_sourceImg.Width > w)
{
t = (double)w;
}
else
{
t = (double)_sourceImg.Width;
}
if ((double)_sourceImg.Height * (double)t / (double)_sourceImg.Width > (double)h)
{
_newH = (double)h;
_newW = (double)h / (double)_sourceImg.Height * (double)_sourceImg.Width;
}
else
{
_newW = t;
_newH = (t / (double)_sourceImg.Width) * (double)_sourceImg.Height;
}
System.Drawing.Image bitmap = new System.Drawing.Bitmap((int)_newW, (int)_newH);
Graphics g = Graphics.FromImage(bitmap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(_sourceImg, new Rectangle(0, 0, (int)_newW, (int)_newH), new Rectangle(0, 0, _sourceImg.Width, _sourceImg.Height), GraphicsUnit.Pixel);
_sourceImg.Dispose();
g.Dispose();
try
{
bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch
{
}
bitmap.Dispose();
}
#endregion