#region 3.1.3 保存裁剪后的图片方法 +ContentResult TemplateCropImg() ////// 保存裁剪后的图片方法 /// ///[HttpPost] public ContentResult TemplateCropImg() { string imageUrl = Request.Form["imgUrl"]; //要剪裁图片的地址 int imageWidth = Convert.ToInt32(Request.Form["imgInitW"]); //原图宽度 int imageHeight = Convert.ToInt32(Request.Form["imgInitH"]); //原图高度 int imageW = Convert.ToInt32(Math.Round(Convert.ToDouble(Request.Form["imgW"]))); //缩放后宽度 int imageH = Convert.ToInt32(Math.Round(Convert.ToDouble(Request.Form["imgH"]))); //缩放后高度 int cropWidth = Convert.ToInt32(Request.Form["cropW"]); //剪裁宽度 int cropHeight = Convert.ToInt32(Request.Form["cropH"]); //剪裁高度 int x = Convert.ToInt32(Request.Form["imgX1"]); //剪裁时X坐标 int y = Convert.ToInt32(Request.Form["imgY1"]); //剪裁时Y坐标 string returnData = string.Empty; //原始图片 using (Image image = Image.FromFile(Server.MapPath(imageUrl))) { //将图片缩放 Bitmap bitmap = new Bitmap(imageW, imageH); Graphics graph = Graphics.FromImage(bitmap); //设置画布的描绘质量 graph.CompositingQuality = CompositingQuality.HighQuality; graph.SmoothingMode = SmoothingMode.HighQuality; graph.InterpolationMode = InterpolationMode.HighQualityBicubic; graph.DrawImage(image, new Rectangle(0, 0, imageW, imageH), new Rectangle(0, 0, imageWidth, imageHeight), GraphicsUnit.Pixel); MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp); //缩放后的图片 Image zoomImage = Image.FromStream(memoryStream); //将缩放后的图片进行裁剪 bitmap = new Bitmap(cropWidth, cropHeight); graph = Graphics.FromImage(bitmap); //清空画布并以透明背景色填充 graph.Clear(Color.Transparent); graph.DrawImage(zoomImage, 0, 0, new Rectangle(x, y, cropWidth, cropHeight), GraphicsUnit.Pixel); //得到裁剪后的图片 string filePath = System.Configuration.ConfigurationManager.AppSettings["UploadDir"] + DateTime.Now.ToString("yyyyMMdd") + "/"; if (!Directory.Exists(Server.MapPath(filePath))) { Directory.CreateDirectory(Server.MapPath(filePath)); } string fileName = filePath + DateTime.Now.Ticks + ".png"; bitmap.Save(Server.MapPath(fileName), System.Drawing.Imaging.ImageFormat.Png); graph.Dispose(); bitmap.Dispose(); returnData = "{'status':'success','url':'" + fileName + "'}"; } //删除之前上传的图片 System.IO.File.Delete(Server.MapPath(imageUrl)); return Content(returnData); } #endregion