C#裁剪图片 需实现一个上传裁剪头像功能 记录以下代码 以备后用
int x1=0;//从X坐标开始
int y1=0;//从Y坐标开始
//获取图片
System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(Server.MapPath(img_src));
//用于缩小图片尺寸
System.Drawing.Bitmap bitmap2 = null;
//新建一个bmp图片 指定裁剪大小
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(114, 145);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以白色填充
g.Clear(Color.White);
//如果图片尺寸大于 条件 则 缩小图片 后进行裁剪
if (imgPhoto.Height > 290 || imgPhoto.Width > 228)
{
bitmap2 = new Bitmap(imgPhoto, 228, 290);
}
//是否进行缩小裁剪
if (bitmap2 != null)
{
g.DrawImage(bitmap2, new Rectangle(0, 0, bitmap2.Width, bitmap2.Height), new Rectangle(x1, y1, bitmap2.Width, bitmap2.Height), GraphicsUnit.Pixel);
}
else
{
g.DrawImage(imgPhoto, new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height), new Rectangle(x1, y1, imgPhoto.Width, imgPhoto.Height),
GraphicsUnit.Pixel);
}
try
{
//图片存储路径
string img_src2 = UrlConfig.PersonLogo + PersonSession.GetUserModel().ID + ".jpg";
bitmap.Save(Server.MapPath(img_src2), System.Drawing.Imaging.ImageFormat.Jpeg);
imgPhoto.Dispose();
if (bitmap2 != null)
{
bitmap2.Dispose();
}
bitmap.Dispose();
g.Dispose();
}
catch (System.Exception e)
{
}
finally
{
if (bitmap2 != null)
{
bitmap2.Dispose();
}
imgPhoto.Dispose();
bitmap.Dispose();
g.Dispose();
}