面向对象设计经典案例,海报生成程序
直接上代码了,主要是做一个根据不同条件做海报生成的程序,如果不用面向对象设计会在程序里加入太多的判断,导致写出无法维护的代码:
[HttpPost("Base64ToImgFile")] public IActionResult Base64ToImgFile([FromForm]string strJson) { dynamic m= Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(strJson); string Base64 = m.Base64; Base64 = Base64.Replace("data:image/jpeg;base64,", ""); int Sex = m.Sex; NewYearBabyService ns = new NewYearBabyService(Sex); string basePath = "resource\\images\\public\\image\\"; string posterPath = _AppConfigurtaionServices.AppConfigurations.UploadFileDir + basePath+ ns.GetImgName();//男女用不同的图 Bitmap bitmapbg = new Bitmap(1080, 1920); Bitmap image = new Bitmap(posterPath); Bitmap headImage = YLYUN.Core.Helper.FileHelper.Base64ToImage(Base64); Graphics graph = Graphics.FromImage(bitmapbg); //graph.DrawImage(headImage, 30, 800); //直接嵌入 headImage = YLYUN.Core.Helper.FileHelper.CutEllipse(headImage, new Rectangle(0, 0, 620, 620), new Size(ns.HeadSizeWidth,ns.HeadSizeHeight)); //Bitmap bitmapbg = new Bitmap(100, 100); //Bitmap image = YLYUN.Core.Helper.FileHelper.Base64ToImage(); //Graphics graph = Graphics.FromImage(image); //graph.DrawImage(image, 0, 0); graph.DrawImage(headImage, ns.HaedX, ns.HaedY); //转换圆形后嵌入 graph.DrawImage(image, 0, 0, 1080, 1920); //graph.DrawImage(bitmapbg, 100, 480); //转换圆形后嵌入 graph.Dispose(); string savaPath = basePath + Guid.NewGuid().ToString() + ".jpg"; string FilePath = _AppConfigurtaionServices.AppConfigurations.UploadFileDir + savaPath; bitmapbg.Save(FilePath); //FileStream fs = new FileStream(Base64); //拿到裁剪图片与底图融合成新图片 return Ok(_AppConfigurtaionServices.AppConfigurations.ResourceUrlPath + savaPath); }
支撑的参数类:
public NewYearBabyService(int Sex) { this.Sex = Sex; } public const string BoyImg = "BabyBoy"; public const string GirlImg = "BabyGirl"; public const string ImgExt = ".png"; public int Sex { get; set; } public int HaedX { get { if (this.Sex==1) { return 315; } else { return 335; } } } public int HaedY { get { if (this.Sex == 1) { return 915; } else { return 898; } } } public int HeadSizeWidth { get { if (this.Sex == 1) { return 430; } else { return 410; } } } public int HeadSizeHeight { get { if (this.Sex == 1) { return 430; } else { return 410; } } } public string GetImgName() { Random rd = new Random(Guid.NewGuid().GetHashCode()); int num = rd.Next(1, 4); string str = this.Sex == 1 ? BoyImg : GirlImg; return string.Format("{0}{1}{2}", str, num, ImgExt); }