C#.Net如何检测圆形遮罩Bitmap已存在避免重复执行遮罩逻辑
C# 圆形遮罩逻辑按需执行实现方案
核心逻辑是提前构造圆形遮罩后的图片存储路径,先判断该路径文件是否已存在,仅当不存在时才执行原图下载、遮罩计算、保存流程,存在则直接读取已生成的遮罩图片使用。
具体修改后代码
if (!String.IsNullOrEmpty(profileImage)) { try { // 先构造原图和圆角图的存储路径 string originalLogoName = profileImage.Remove(0, profileImage.LastIndexOf('/') + 1); string originalLogoPath = Path.Combine(PathW, @"Content\generate\exitlogo\", originalLogoName); string roundedLogoPath = originalLogoPath.Replace(".png", "rounded.png"); PdfImage NewImgsample; // 先判断圆角图是否已经存在,存在直接用 if (File.Exists(roundedLogoPath)) { NewImgsample = PdfImage.FromFile(roundedLogoPath); } else { // 圆角图不存在,走原图下载+遮罩处理逻辑 bool originalFileExists = File.Exists(originalLogoPath); byte[] imageBytes = originalFileExists ? File.ReadAllBytes(originalLogoPath) : webClient.DownloadData(profileImage); if (!originalFileExists) { File.WriteAllBytes(originalLogoPath, imageBytes); } using (MemoryStream ms = new MemoryStream(imageBytes)) using (Bitmap OrgImg = new Bitmap(ms)) using (Bitmap NewImg = new Bitmap(OrgImg.Width, OrgImg.Height)) { for (int y = 0; y <= OrgImg.Height - 1; y++) { for (int x = 0; x <= OrgImg.Width - 1; x++) { if ((Math.Pow(x - (OrgImg.Width / 2), 2) + Math.Pow(y - (OrgImg.Width / 2), 2)) < Math.Pow(OrgImg.Width / 2, 2)) { NewImg.SetPixel(x, y, Color.FromArgb(255, OrgImg.GetPixel(x, y).R, OrgImg.GetPixel(x, y).G, OrgImg.GetPixel(x, y).B)); } else { NewImg.SetPixel(x, y, Color.Empty); } } } // 保存圆角图 NewImg.Save(roundedLogoPath); NewImgsample = PdfImage.FromFile(roundedLogoPath); } } // 插入PDF逻辑 foreach (PdfPage page in doc.Pages) { page.Graphics.DrawImage(NewImgsample, 686.211f, 247.0f, 101.389f, 101.389f); } NewImgsample.Dispose(); } catch (Exception ex) { // 建议此处添加异常日志,避免吞错导致问题无法排查 } }
额外优化说明
- 替换了字符串拼接路径为
Path.Combine,避免不同系统下路径分隔符不兼容问题 - 新增
using语句管理非托管资源(MemoryStream、Bitmap等),无需手动调用Dispose,避免内存泄漏 - 补全了异常捕获参数,方便后续排查问题时定位错误原因
内容的提问来源于stack exchange,提问作者farnaz
相关产品推荐
相关产品推荐

