#region Base64解码图片 // <summary> /// 图片上传 Base64解码 /// </summary> /// <param name="dataURL">Base64数据</param> /// <returns>返回一个相对路径</returns> public JsonResult DecodeBase64ToImageByPictorialSentencePhoto(string baseUrl) { baseUrl = baseUrl.Substring(baseUrl.IndexOf(",") + 1); byte[] bt = Convert.FromBase64String(baseUrl);//获取图片base64 string ImageFilePath = "Upload/PictorialSentencePhoto/" + DateTime.Now.ToString("yyyyMMdd"); string filePath = ""; using (var ms = new MemoryStream(bt)) { Bitmap bmp = new Bitmap(ms);
//直接限定图片的宽高 int max_Left = 0; int min_Right =427; int max_Bottom = 748; int min_Top = 0; //最左邊黑邊:0,最右邊黑邊:427 //最上邊黑邊:0,最下邊黑邊:748 //创建一个画框:宽(右黑边起始位置-左黑边最终位置=去除黑边之后的宽度),高(整个图片 的图框) Bitmap huakuang = new Bitmap(min_Right - max_Left, max_Bottom-min_Top); //创建一个画布:宽高和画框一致 Graphics huabu = Graphics.FromImage(huakuang); //清空画布(透明) huabu.Clear(System.Drawing.Color.Transparent); //画布上所要画的位置和大小 RectangleF huabu_rec = new RectangleF(0, 0, min_Right - max_Left, max_Bottom - min_Top); //图片所要裁剪矩形的大小和位置: //x=intLeft(从左黑边最终位置开始),y=0 //width=intRight - intLeft(右黑边起始位置-左黑边最终位置=去除黑边之后的宽度),height=整个图片的高 RectangleF img_rec = new RectangleF(max_Left, 0, min_Right - max_Left, max_Bottom - min_Top); //在画布上的指定位置大小(huabu_rec)画上图片(bmp)的指定部分(img_rec) huabu.DrawImage(bmp, huabu_rec, img_rec, GraphicsUnit.Pixel); if (Directory.Exists(hostingEnvironment.WebRootPath + @"/" + ImageFilePath) == false)//如果不存在就创建文件夹 { Directory.CreateDirectory(hostingEnvironment.WebRootPath + @"/" + ImageFilePath); } string fileName = System.DateTime.Now.ToString("yyyyHHddHHmmss") + ".png"; filePath = @"/" + ImageFilePath + @"/" + fileName;//获取保存后的相对路径 huakuang.Save(hostingEnvironment.WebRootPath + @"/" + ImageFilePath + "/" + fileName, System.Drawing.Imaging.ImageFormat.Png); } return Json(new Result { ReturnValue = filePath });//返回相对路径 } #endregion
标签:huabu,min,C#,max,base64,new,字符串,rec,图片 From: https://www.cnblogs.com/QiangQiangDai/p/17474671.html